Prepared statement fails in a function - PHP - php

I don't know why but this function returns false when I try to use prepared statements in it however, when I use non-prepared statements it returns true. Can anyone explain it?
Code:
function evalLoggedUser($conx,$id,$u,$p){
$sql = "SELECT ip FROM users WHERE id=? AND username=? AND password=? AND activated=? LIMIT 1";
$stmt = $conx->prepare($sql);
$var = 1;
$stmt->bind_param("issi",$id,$u,$p,$var);
$stmt->execute();
$numrows = $stmt->num_rows;
if($numrows > 0){
return true;
}
$stmt->close();
}
$user_ok = evalLoggedUser($conn,$log_id,$log_username,$log_password);
This returns false
function evalLoggedUser($conx,$id,$u,$p){
$sql = "SELECT ip FROM users WHERE id='$id' AND username='$u' AND password='$p' AND activated='1' LIMIT 1";
$query = mysqli_query($conx, $sql);
$numrows = mysqli_num_rows($query);
if($numrows > 0){
return true;
}
}
$user_ok = evalLoggedUser($conn,$log_id,$log_username,$log_password);
This returns true

The problem is a simple typographical mistake: you pass 4 parameters as prepared, but expect 5.
See this: $stmt->bind_param(/*"issi",*/$id,$u,$p,$var);

Related

Equivalent function num_rows in MYSQL for PDO for use with SQL-server [duplicate]

Right now I have a PHP file that does a MYSQL query and then counts rows like this:
$count=mysql_num_rows($result);
if ($count == 1) {
$message = array('status' => 'ok');
} else {
$message = array('status' => 'error');
}
This works fine but I'm trying to change all my PHP files to use PDO. So how can this be done with PDO?
$res = $DB->query('SELECT COUNT(*) FROM table');
$num_rows = $res->fetchColumn();
or
$res = $DB->prepare('SELECT COUNT(*) FROM table');
$res->execute();
$num_rows = $res->fetchColumn();
You can use this to ask if data exists or is selected, too:
$res = $DB->query('SELECT COUNT(*) FROM table');
$data_exists = ($res->fetchColumn() > 0) ? true : false;
Or with your variables:
$res = $DB->query('SELECT COUNT(*) FROM table');
$message = ($res->fetchColumn() > 0) ? array('status' => 'ok') : array('status' => 'error');
$stmt = $db->query('SELECT * FROM table');
$row_count = $stmt->rowCount();
echo $row_count.' rows selected';
Maybe you can use PDO's "fetchAll" method, which returns an array containing all the SELECT results.
Then use "count" method to count the array's rows.
Ex:
$rows = $stmt->fetchAll();
$num_rows = count($rows);
If you are not using prepared statements then try:
$find = $dbh->query('SELECT count(*) from table');
if ($find->fetchColumn() > 0){
echo 'found';
}
However, if you choose prepared statements, which i highly recommend, then:
$find = $dbh->prepare('SELECT count(*) from table');
$find->execute();
if ($find->fetchColumn() > 0){
echo 'found';
}
Can be like that...
$numRows = $conn->query("SELECT COUNT(*) FROM yourtable")->fetchColumn();
echo $numRows;

New SQL PDO query from result

I'm very new to PDO SQL queries. I have the following code which works well. When the result returns only 1 row, I then want to set that row to valid = FALSE". How do I do that?
$sql = "SELECT * FROM `passcodes` WHERE `passcode` = '$passcode' AND `valid` = TRUE";
$stmt = $DBcon->prepare($sql);
$stmt->execute();
$count = $stmt->rowCount();
if($count == 1) {
//do this
} else {
//do that
}
Yet another solution.
IF you interested in "else" section mentioned above, you can combine elegant solution from #YourCommonSense with checking how much rows was changed in UPDATE. MySQL returns such info!
$sql = "UPDATE `passcodes` SET `valid` = FALSE WHERE `passcode` = ? AND `valid` = TRUE";
$DBcon->prepare($sql)->execute([$passcode]);
if ($stmt->rowCount() == 0) {
// do this when nothing found
}
I then want to set that row to valid = FALSE". How do I do that?
this is what SQL is for.
$sql = "UPDATE `passcodes` SET `valid` = FALSE WHERE `passcode` = ? AND `valid` = TRUE";
$DBcon->prepare($sql)->execute([$passcode]);
this is all the code you need.
This will work with count of result rows equal or greater than 1.
I recommend to use placeholders for prepared statements:
$sql = "SELECT `id` FROM `passcodes` WHERE `passcode` = ? AND `valid` = TRUE";
$stmt = $DBcon->prepare($sql);
$stmt->execute([ $passcode ]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
if($rows) {
//do this
$sql = "UPDATE `passcodes` SET `valid` = FALSE WHERE `id` = ?";
$stmt = $DBcon->prepare($sql);
foreach ($rows as $r) {
$stmt->execute([ $r['id'] ]);
}
} else {
//do that
}

Cannot make an SQL query work from PHP

i'm trying to run a very simple PHP function :
function evalLoggedUser($db_conx,$id,$e,$p){
$sql = "SELECT ip FROM users WHERE id={$id} AND email= '$e' AND password= '$p' AND activated=1 LIMIT 1 ";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
if($numrows > 0){
return true;
} else {
echo $sql;
}
}
as part of a user authentication. The problem is that the query is not working and I dont know why! I know the mysql connection is working as I have checked the mysqli_errno and not getting anything there - Can anyone help?
Try this one..
function evalLoggedUser($db_conx,$id,$e,$p){
$sql = "SELECT ip FROM users WHERE id='$id' AND email= '$e' AND password= '$p' AND activated=1 LIMIT 1 ";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
if($numrows > 0){
return true;
} else {
echo $sql;
}
}
Values gets substituted by default inside double quotes. But make sure you check the connection too.
$sql = "SELECT ip FROM users WHERE id=$id AND email= $e AND password= $p AND activated=1 LIMIT 1 ";

mysqli if result > 0 do something

How would i do this using mysqli?
$SQL = mysql_query("SELECT username FROM users WHERE username = '$new_username'");
$result = mysql_num_rows($SQL);
If(!$result > 0) {
echo...
I tried:
$SQL = $mysqli->query("SELECT username FROM users WHERE username = '$utilizator");
$rezultat->num_rows($SQL);`
But I dont get any result.
You have started the query with $SQL .. continue with it as the object will be in that variable:
$SQL = $mysqli->query("SELECT username FROM users WHERE username = '$utilizator'");
$num = $SQL->num_rows();
if($num){
// run your code here
}
you have to call store_result() after execution.
php.net has a wonderful php doc: http://www.php.net/manual/de/mysqli-stmt.num-rows.php
for example:
$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = $mysqli->prepare($query)) {
/* execute query */
$stmt->execute();
/* store result */
$stmt->store_result();
printf("Number of rows: %d.\n", $stmt->num_rows);
/* close statement */
$stmt->close();
}
$number_of_rows = $SQL->num_rows;

Checking if mysql_query returned anything or not

$query = "SELECT * FROM `table`";
$results = mysql_query($query, $connection);
If 'table' has no rows. whats the easiest way to check for this.?
Jeremy Ruten's answer above is good and executes quickly; on the other hand, it only gives you the number of rows and nothing else (if you want the result data, you have to query the database again). What I use:
// only ask for the columns that interest you (SELECT * can slow down the query)
$query = "SELECT some_column, some_other_column, yet_another_column FROM `table`";
$results = mysql_query($query, $connection);
$numResults = mysql_num_rows($results);
if ($numResults > 0) {
// there are some results, retrieve them normally (e.g. with mysql_fetch_assoc())
} else {
// no data from query, react accordingly
}
You could use mysql_num_rows($results) to check if 0 rows were returned, or use this faster alternative:
$query = "SELECT COUNT(*) AS total FROM table";
$results = mysql_query($query, $connection);
$values = mysql_fetch_assoc($results);
$num_rows = $values['total'];
Alternatively you can simply check if the result of mysql_fetch_assoc is false.
$query = "SELECT * FROM `table`";
$results = mysql_query($query, $connection);
$Row = mysql_fetch_assoc($results);
if ($Row == false)
{
$Msg = 'Table is empty';
}
One thing i noticed that was missed was the fact that the query might not succeed, so you do need to check if the $results variable is set. I'll use the answer given by yjerem as an example.
$query = "SELECT COUNT(*) AS total FROM table";
$results = mysql_query($query, $connection);
if ($results) { // or use isset($results)
$values = mysql_fetch_assoc($results);
$num_rows = $values['total'];
}
If you loop through the results, you can have a counter and check that.
$x = 1;
$query = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_assoc($query))
{
$x++;
}
if($x == 1)
{
//No rows
}

Categories