i need get result row count
$this-> db = new mysqli("localhost", "***", "***", "***") or die("Error ".mysqli_error($link));
$this-> db -> set_charset("utf8");
$query = "SELECT steps.id, steps.description, steps.sort, services.`name` AS service_name, services.short_name AS service_short_name, terminals.`name` AS terminal_name, terminals.short_name AS terminal_short_name FROM steps INNER JOIN instructions ON steps.page_id = instructions.id INNER JOIN services ON instructions.service_id = services.id INNER JOIN terminals ON instructions.terminal_id = terminals.id WHERE services.short_name = '{$service}' AND terminals.`name` = '{$terminal}' ORDER BY steps.sort";
if ($stmt = $this->db-> prepare($query)) {
$stmt -> execute();
$stmt -> store_result();
printf("row count: %d.\n", $stmt -> num_rows);
$stmt -> close();
}
it returns zero - 0 but there are some like 10-15 rows
Although "What I do incorrect" is an offtopic question for this site, the answer is:
Speaking of getting number of rows, you are doing everything correct.
The only cause for your troubles is some data/code inconsistency which you have to solve yourself.
Speaking of using prepared statements, you are using them wrong, adding variables directly into query while you ought to represent them with placeholders and bind later.
Related
I am working on the following script. Why am I always getting 0 using the COUNT(*) in my query against MySQL using prepared statement?
$num_query = "SELECT COUNT(*) FROM $tbl WHERE `tdisplay` = 1";
$stmt2 = $conn-> prepare($num_query);
$stmt2 -> execute();
$stmt2 -> store_result();
$rows = $stmt2->num_rows;
I have this code
$con = new mysqli('####', '####', '####', '####');
if(mysqli_connect_errno()){
echo 'Connection Failed:' . mysqli_connect_errno();
exit();
}
//Variables
$user = $_POST['username'];
$zone = $_POST['password'];
$pass = strtoupper(hash("whirlpool", $zone));
//Prepare
if($stmt = $con -> prepare("SELECT * FROM `accounts` WHERE Username=? AND Key=?")){
$stmt -> bind_param("ss", $user, $pass);
$stmt -> execute();
$stmt -> bind_results($result);
$stmt -> fetch();
if($result) {
$_SESSION['username'] = $user;
$url = 'home.php';
echo '<META HTTP-EQUIV=Refresh CONTENT="1; URL='.$url.'">';
} else {
echo 'Login Failed';
}
}
?>
I am new to Prepared statements and I cannot get it to work.
Upon trying to log in I just get a blank white page with no error. I know I am connected to the db because if I remove the prepared statement and do it the unsecured way everything logs in just fine.
Please note. I have just been looking up tutorials on prepared statements so I can learn to code more securely. I am in no way a pro with this. Any tips would be greatly appreciated.
Warning: mysqli_stmt::bind_result(): Number of bind variables doesn't
match number of fields in prepared statement in
C:\xampp\htdocs\newsystem\loginadd.php
That's because you select * (all fields). You should be more specific about the fields you want to get (for example SELECT id FROM ...).
Have a look at examples on PHP doc: 2 fields are selected, 2 parameters for bind_result().
According to #AbrikChakraborty comment you just need add backticks to your field name:
if($stmt = $con -> prepare("SELECT * FROM `accounts` WHERE Username=? AND `Key`=?")){
and according to #caCtus comment:
$stmt -> bind_result($result);
and if you really want to bind unknown number of fields returned you can check this answer or just use PDO.
Verify the actual query, if it fetches the result. I doubt the query itself returns empty result.
"SELECT * FROM `accounts` WHERE Username=$user AND Key=$pass"
I'm trying to get to grips with mysqli but finding it a struggle compared to the now depreciated mysql. So far with the old methods I've been able to get information back about my tables in an associative array. I'm trying to form a prepared statement and echo the id number back. I would also like to be able to print the whole sql statement that has been binded, but seen as I can't even echo the id number from a single SELECT statement, it is out of the question at the moment.
$db = new mysqli('xxx', 'xx', 'xx', 'xxxx');
$sql = "SELECT user_id, name FROM users WHERE name=?"
$statement = $db -> prepare($sql);
$statement -> bind_param("s", "Emma");
$statement -> execute();
$statement -> bind_result($id, $name);
$output = $statement -> fetch();
echo $output -> $id . " " . $name;
I seem to be getting lost at the line bind_result. I figured if statement is an object, then I should be able to echo them in the form I have devised? When I refresh my page I just get nothing. I have 2 entries in my table and 1 of them does have the name string that is used above.
You think too complex. Just try this:
$db = new mysqli('xxx', 'xx', 'xx', 'xxxx');
$sql = "SELECT user_id, name FROM users WHERE name=?";
$statement = $db->prepare($sql);
$statement->bind_param("s", "Emma");
$statement->execute();
$statement->bind_result($id, $name);
while ($statement->fetch()) {
echo $id . " " . $name;
}
The bind_result() methods takes care that for each $statement->fetch() you execute you get fresh values in the variables $id and $name.
You should take a look at the good documentation of those methods.
I'm just trying to figure out how to determine the number of rows and then make that number display in the HTML.
My prepared statement looks like this:
if($stmt = $mysqli -> prepare("SELECT field1, field2, field3 FROM table WHERE id= ?ORDER BY id ASC"))
{
/* Bind parameters, s - string, b - blob, i - int, etc */
$stmt -> bind_param("i", $id);
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($testfield1, $testfield2, $testfield3);
/* Fetch the value */
$stmt -> fetch();
/* Close statement */
$stmt -> close();
}
I understand that I'm supposed to first save the results, then use num_rows, like this:
$stmt->store_result();
$stmt->num_rows;
However, I'm running, and issue with the page bugging out when I put that code in there. I haven't even been able to get to the next step of how to display the number of rows
What am I missing in terms of calculating the number of rows inside the prepared statement, then how would I display it with a <?php echo '# rows: '.$WHATGOESHERE;?>
num_rows returns the number, you have to store it in a variable.
/*.....other code...*/
$numberofrows = $stmt->num_rows;
/*.....other code...*/
echo '# rows: '.$numberofrows;
So full code should be something like this:
$stmt = $mysqli -> prepare("SELECT field1, field2, field3 FROM table WHERE id= ? ORDER BY id ASC");
/* Bind parameters, s - string, b - blob, i - int, etc */
$stmt -> bind_param("i", $id);
$stmt -> execute();
$stmt -> store_result();
/* Bind results */
$stmt -> bind_result($testfield1, $testfield2, $testfield3);
/* Fetch the value */
$stmt -> fetch();
$numberofrows = $stmt->num_rows;
/* Close statement */
$stmt -> close();
echo '# rows: '.$numberofrows;
If you are only interested in the row count instead of the actual rows of data, here is a complete query block with a COUNT(*) call in the SELECT clause.
$conn = new mysqli("host", "user", "pass", "db");
$stmt = $conn->prepare("SELECT COUNT(*) FROM `table` WHERE id= ?");
$stmt->bind_param("s", $id);
$stmt->execute();
$stmt->bind_result($num_rows);
$stmt->fetch();
echo $num_rows;
Or if you want to know the row count before iterating/processing the rows, one way is to lump the entire resultset (multi-dimensional array) into a variable and call count() before iterating.
$conn = new mysqli("host", "user", "pass", "db");
$sql = "SELECT field1, field2, field3
FROM table
WHERE id= ?
ORDER BY id";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $id);
$stmt->execute();
$result = $stmt->get_result();
$resultset = $result->fetch_all(MYSQLI_ASSOC);
echo "<div>Num: " , count($resultset) , "</div>";
foreach ($resultset as $row) {
echo "<div>Row: {$row['field1']} & {$row['field2']} & {$row['field3']}</div>";
}
*I have tested both of the above snippets to be successful on my localhost.
This works as of Feb 2020:
$number_of_records = $stmt->rowCount();
echo $number_of_records;
From php.net manual:
PDOStatement::rowCount() returns the number of rows affected by a
DELETE, INSERT, or UPDATE statement.
Here is an example from their website:
<?php
/* Delete all rows from the FRUIT table */
$del = $dbh->prepare('DELETE FROM fruit');
$del->execute();
/* Return number of rows that were deleted */
print("Return number of rows that were deleted:\n");
$count = $del->rowCount();
print("Deleted $count rows.\n");
?>
The above example will output:
Return number of rows that were deleted:
Deleted 9 rows.
Check out the example #2 here:
PHP.net
Use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.
I have 3 different queries, some work and some don't.
I know pdo select does not work with mysql so why do these work?
$q = $dbc -> prepare("SELECT * FROM accounts WHERE id = ?");
$q -> execute(array($user['id']));
echo $q -> rowCount();
Returns correct data, If I add another param it doesn't,
$q = $dbc -> prepare("SELECT * FROM accounts WHERE id = ? && age = 12");
$q -> execute(array($user['id']));
echo $q -> rowCount();
It fails returning zero, again this query works and correctly displays the rows matched;
$q = $dbc -> prepare("SELECT * FROM accounts WHERE id = ? && username = ? && logCount = -1");
$q -> execute(array($user['id'], $user['username']));
Why do some work and others don't?
echo $q -> rowCount();
As per the fine manual, rowCount() is defined only for DML queries: INSERT, UPDATE, or DELETE. The manual states that SELECT queries are "not guaranteed for all databases" and in fact MySQL support is not reliable.
Second query either fails with error or just unable to find rows to match WHERE condition.
To reveal the first cause, add this line to connection code.
$dbc->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );