Select Mysql for PDO?

Does anyone know the equivalent of this select in PDO?

$sql = “SELECT * FROM users WHERE username=’”.$username."’ AND password=’".$password."’ LIMIT 1 ";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) == 1) {
$row = mysql_fetch_assoc($res);

I have this solution so far :

$select=$pdo->prepare(" SELECT * FROM users WHERE username=’".$username."’ AND password=’".$password."’ LIMIT 1 ");
$select->execute();
$linha=$select->fetchAll(PDO::FETCH_ASSOC);
foreach($linha as $row ){

How to replace “if (mysql_num_rows ($ res) == 1) {” ?

Hi @VOLTAREDONDA!

If I would knew PDO, I would truly help you, however I don’t know. As far as I know, PDO is better at returning different results, however I would use mysqli_* instead, which is far more simple and has future support as well:

$connection = mysqli_connect("localhost", "username", "password", "database"); // connect and select DB at the same time

$sql = "SELECT * FROM users WHERE username='".$username."' AND password='".$password."' LIMIT 1 ";

$res = mysqli_query($connection, $sql) or die(mysqli_error($connection));

if (mysqli_num_rows($res)  > 0) 
{
        $rows = mysqli_fetch_all($res); // converts object $res into array $rows; $rows is multi-dimensional in this case
     
        print_r($rows); // prints the entire $rows array 

        print("<br><br>");

	foreach($rows as $row => $cols) // walk through array
	{
		foreach($cols as $col => $val) // walk through array
		{
			print($val . "<br>"); // output value of each col
		}
	}

}
else
{
   print("No rows returned.");
}

Or better…

$connection = mysqli_connect("localhost", "username", "password", "database"); // connect and select DB at the same time

$sql = "SELECT * FROM users WHERE username='".$username."' AND password='".$password."' LIMIT 1 ";

$res = mysqli_query($connection, $sql) or die(mysqli_error($connection));

if (mysqli_num_rows($res)  > 0) 
{
        $row = mysqli_fetch_row($res); // converts object $res into array $rows;
     
	foreach($row as $col => $val)
	{
		print($val . "<br>");
	}
}
else
{
	print("No row returned.");
}

ok ,
I’m going to test mysqli .
thank you.

Also let us know, if you face any issues, while using mysqli_* function.

This topic was automatically closed after 44 hours. New replies are no longer allowed.