L
L
Lumore2014-11-23 16:11:00
PHP
Lumore, 2014-11-23 16:11:00

Am I doing the SQL query correctly with mysqli ?

$mysqli = new mysqli('localhost', 'root', '', 'system');

function get_posts() {
  global $mysqli;
  $sql = "SELECT * FROM posts";
  $result = $mysqli->query($sql);
  $result = mysqli_fetch_assoc($result);
  return $result;
}

Then I output:
$posts = get_posts();
foreach($posts as $post) {
  echo '
  <div class="post">
    <div class="post-author"><a href="/profile.php?id='.$post['author-id'].'">'.$post['author-name'].' '.$post['author-surname'].'</a></div>
  </div>
  ';
}

As a result, the characters are displayed:
1 1
1 1
� �
� �
0 0
I had such a question, I thought it was about the encoding, but everything is fine with it.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
T
tushev, 2014-11-23
@Lumore

So mysqli_fetch_assoc() only fetches one row, not the entire selection! If you want to get the entire selection, you need to twist the mysqli_fetch_assoc call in a loop. Something like that

while ($row = $result->fetch_assoc()) {
   ....
}
And you extract one row, and then try to loop through it, thinking that you are looping through the records, but in fact, the loop is spinning through the fields of the first record.

G
Grigory Esin, 2014-11-23
@xotey83

Try to do $mysqli->set_charset('your character set');
There is an option that you do not specify the encoding in the Content-Type HTTP header

F
FanatPHP, 2014-11-23
@FanatPHP

Not right.
It will be correct like this:
1. write in the address bar of the browser mysqli_fetch_assoc
2. In the window that opens, follow the first link
3. Read carefully.
4. We think.
5. We look at examples.
6. We write the correct code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question