0

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,

Kaan
  • 33
  • 3
  • 3
    Use strict comparison operator(`===`), like this: `if($row['Valid'] === 1){ ...` – Rajdeep Paul Feb 02 '16 at 00:42
  • May i ask what's the valid row for? – ern Feb 02 '16 at 00:44
  • Dear @ern, Im just trying to learn the basics but I plan to use it similar to deleting a row. Rather than deleting it, I will change the valid bit to zero so that I can access the old information. – Kaan Feb 02 '16 at 00:46
  • Then just `$row['Valid']` should work for you as an argument in your statement..Since 0 means false. – ern Feb 02 '16 at 00:55

2 Answers2

2

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)
cschaefer
  • 126
  • 7
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";

Edit:

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>";
}
fusion3k
  • 11,568
  • 4
  • 25
  • 47