Warum wird der erste Datensatz in meiner Abfrage nicht angezeigt, wenn ich 'while' verwende, um die Ergebnisse anzuzeigen?PHP: Warum wird der erste Datensatz nicht angezeigt, wenn ich 'while' verwende, um die Ergebnisse anzuzeigen?
Zum Beispiel user_id 1
anmeldet und die contact_id
5 und 6 sind mit meinem Echo am Ende angezeigt mit:
echo "contact is " . $row["contact_id"];
Hier ist mein Code:
<?php
require('dbConnect.php');
//I have a contacts table like this :
//contact_auto_inc user_id contact_id
// 1 1 3
// 2 1 5
// 3 2 1
// 4 3 5
// 5 3 2
// 6 1 6
//The user logs in and their user_id is displayed at the top of the page with code like the following :
//use the variables we created earlier
session_start();
$user_id = $_SESSION['user_id'];
echo "user id is " . $user_id . "<br>";
//So if user_id 1 logs in, we see at the top of the page "user id is 1"
//I want to display the list of contacts for the logged in user_id
$select_from_contacts_table = "SELECT * FROM contacts WHERE user_id = '$user_id'";
//get the result of the above
$result=mysqli_query($con,$select_from_contacts_table);
//get every other record in the same row as that particular user_id
$row = mysqli_fetch_assoc($result);
// get the matching contact_id in each row
//$contact_id = $row["contact_id"];
while($row = mysqli_fetch_assoc($result)) {
//$contact_id=$rows['contact_id'];
echo "contact is " . $row["contact_id"] . "<br>";
}
?>
Sie holen (und überschreiben ...) die erste Zeile direkt vor der Schleife. – jeroen
** WARNUNG **: Wenn Sie 'mysqli' verwenden, sollten Sie [parametrisierte Abfragen] (http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) und [' bind_param'] (http://php.net/manual/en/mysqli-stmt.bind-param.php), um Benutzerdaten zu Ihrer Abfrage hinzuzufügen. ** Verwenden Sie NICHT ** String-Interpolation oder Verkettung, um dies zu erreichen, weil Sie einen schwerwiegenden [SQL injection bug] erstellt haben (http://bobby-tables.com/). ** NIEMALS ** $ _POST 'oder' $ _GET' Daten direkt in eine Abfrage einfügen, es kann sehr schädlich sein, wenn jemand versucht, Ihren Fehler auszunutzen. – tadman