This question already has an answer here:
Hello I'm new to php and mySQL. Basically I have a table of users and I want to echo the id, name and surname of the users if their "valid" integer is equal to 1, here is my attempt;
<?php
$servername = "aaa";
$username = "aaa";
$password = "aaa";
$dbname = "aaa";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ID, Name, Surname, Valid FROM myTable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if($row["Valid"] = 1) {echo "id: " . $row["ID"]. " - Name: " . $row["Name"]. " " . $row["Surname"]. "<br>";
}
}
} else {
echo "0 results";
}
$conn->close();
?>
Using this code gives me a list of all the users, even though their valid integers are zero.
Thanks,
</div>
In PHP to check for conditions as you are you need the == operator instead of the = operator. All you are doing is setting all the valid columns to 1.
if($row["Valid"] == 1)
You have to add a WHERE
condition to your query:
$sql = "SELECT ID, Name, Surname, Valid FROM myTable WHERE Valid=1";
If you query select all fields of table, you can also perform the query as:
$sql = "SELECT * FROM myTable WHERE Valid=1";
As suggested by my dears and accurate censors in the comments below, if you use my suggested solution, the check of $row[Valid]
in the while
loop, although not invalidate the result, is totally unnecessary.
So - to obtain the list of users with field Valid
= 1, you can write in this simple way:
while( $row = $result->fetch_assoc() )
{
echo "id: " . $row["ID"]. " - Name: " . $row["Name"]. " " . $row["Surname"]. "<br>";
}