PHP echo total number of rows from SQL query - php

I'm not sure where I'm going wrong here. I've searched similar issues on here with no luck. Any help would be greatly appreciated. Thanks!
$check = "SELECT Number FROM advisors";
$result = mysqli_query($check);
$count = mysqi_num_rows($result);
echo $count;

You should use php prepare statement like this
$count = 0;
$mysqli = new mysqli(host, dbUser, dbPassword, dbName);
mysqli_set_charset($mysqli, "utf8");
$sql = "select count(*) from advisors";
if ($stmt = mysqli_prepare($mysqli, $sql))
{
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $c);
if (mysqli_stmt_fetch($stmt))
{
$count = $c;
}
mysqli_stmt_close($stmt);
}
return $count;
For more information, here is the link for php prepare statement
Documentation of php prepare statement

You should use COUNT in query and see if it works,
"SELECT COUNT (number) as number FROM advisors";
By the way, I noticed a typo in $count, it should be $count = mysqli_num_count($result).

Related

PHP Multiple Prepared Statements

I would like to execute two statements and print the results within a while loop. Each statement will select data from two different tables.
I'm not sure the best way to approach this.
My code so far is as follows;
$conn = new mysqli('localhost', 'user', 'password', 'db');
if ($conn->connect_errno > 0) {
die('Unable to connect to database [' . $conn->connect_error . ']');
}
$curDate = date("Y-m-d");
//first stmt
$stmt = $conn->prepare("SELECT start, status FROM log WHERE start >= ?");
$stmt->bind_param('s', $curDate);
$stmt->execute();
$stmt->bind_result($start, $status);
$stmt->close();
//second stmt
$stmt = $conn->prepare("SELECT time FROM params");
$stmt->bind_result($time);
$stmt->execute();
$stmt->close();
/* fetch values and echo for testing */
while ($stmt->fetch()) {
echo $start;
echo $status;
echo $time;
}
Any help is appreciated.
In general, there is nothing special in running two or dozen prepared statements - you just have run them one by one. Thus there is no "best way" at all.
In your particular case the best way is to get rid of prepared statements:
$time = $conn->query("SELECT time FROM params")->fetch_object()->time;
$res = $conn->query("SELECT start, status FROM log WHERE start >= CURDATE()");
while($row = $res->fetch_object())
{
echo $row->start;
echo $row->status;
echo $time;
}

PHP prepare and execute

I was using the following code to execute the queries in the database:
$sql = "SELECT * FROM cc_topchoices WHERE location='$location' ORDER BY position asc";
$result = mysqli_query($conn, $sql);
I have read that this way to make the queries is not secure so I want to use the statements prepare() and execute() in php
Now my code looks like this:
$sql = "SELECT * FROM cc_topchoices WHERE location=:location ORDER BY position asc";
$stmt = $conn->prepare($sql);
$stmt->execute(array(":location" => $location));
$result = mysqli_query($conn, $stmt);
But this give me this error:
Fatal error: Call to a member function execute() on boolean
Any idea?
EDIT
Now my code looks like this:
// Create connection
$conn = new PDO("mysql:host=$servername;dbname=$dbname", "$username", "$password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("set names utf8"); //BECAUSE I NEED TO WORK WITH CHINESE LANGUAGE
$sql = "SELECT * FROM cc_topchoices WHERE location=? ORDER BY position asc";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':location', $location);
$stmt->execute(array($location));
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
if ($result > 0) {
// output data of each row
while($row = $stmt->fetch()) {
echo "<li><div><a href='". $row["rest_url"] ."'><img src='images/top_choices/". $row["image"] ."' alt='". $row["alt_desc"]. "' /></a></div></li>";
}
} else {
echo "0 results";
}
is working :) just need to know if this is a good and secure practice
PDO supports named parameters. MySQLi does not. $stmt is false to show you that the SQL you tried to prepare is syntactically malformed. Use ? instead of :location. Check the MySQLi manual for the correct way to use MySQLi. Or, alternately, switch to PDO.
Use below code to fetch records instead of mysqli_query when using pdo statements if your query returns single row.
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo $result['db_column'];
And if return multiple rows:
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while ($result = $stmt->fetch()) {
echo $result['db_column'];
}
And one more thing, always put your prepared statement in try{}..catch{} block.
It will work for you.

Prepared statements and mysqli_query / mysqli_num_rows?

I am trying to find out how to make my code work with prepared statements. I understood the entire process up to where I commented my code. What do I have to do in order to integrate num_rows and the mysqli_query part properly?
function login_check() {
global $connection;
$name = $_POST['name'];
$password = $_POST['password'];
$query = "SELECT id FROM members WHERE name = $name AND password = $password";
$stmt = $connection->prepare($query);
$stmt->bind_param('ss', $name, $password);
$stmt->execute();
$stmt->close();
// $result = mysqli_query($connection, $query);
// $rows = mysqli_num_rows($result);
if($rows > 0){
header('location:../../success.php');
exit;
}
else {
header('location:../../failed.php');
exit;
}
}
What I tried:
$result = mysqli_query($connection, $stmt);
$rows = mysqli_num_rows($result);
Change
$query = "SELECT id FROM members WHERE name = $name AND password = $password";
to
$query = "SELECT `id` FROM `members` WHERE `name` = ? AND `password` = ?";
Adding backticks around table and columns prevents mysql reserved words error.
Remove $stmt->close();
if( $stmt->num_rows > 0 ) {
$stmt->close();
header('location:../../success.php');
exit();
} else {
$stmt->close();
header('location:../../failed.php');
exit();
}
Adding $stmt->close() inside if statement before header is best practice in this case.
Becasue adding it before if statement would result in $stmt->num_rows always returning 0; Adding it after the if statment won't work because exit() would prefent it from executing.
From the documentation:
Closes a prepared statement. mysqli_stmt_close() also deallocates the statement handle. If the current statement has pending or unread results, this function cancels them so that the next query can be executed.

mysqli_stmt_num_rows() returns 0 rows

I tried to count return rows from a query using prepared statements.
Something like this :
$q = "SELECT name, address, contact FROM members";
$stmt = mysqli_prepare ($dbc, $q);
mysqli_stmt_store_result($stmt);
// Get the number of rows returned:
$rows = mysqli_stmt_num_rows($stmt);
echo $rows;
But always I am getting 0 rows when executing this query. I tested it using mysql client ant then I got 6 returned rows.
can anyone tell me what is the wrong with this?
Thank you.
You need to call mysqli_stmt_execute to actually get a result set, before trying to store the results.
$stmt = mysqli_prepare ($dbc, $q);
mysqli_stmt_execute($stmt); // <--------- currently missing!!!
mysqli_stmt_store_result($stmt);
$rows = mysqli_stmt_num_rows($stmt);
You have to execute the query
$q = "SELECT name, address, contact FROM members";
if ($stmt = mysqli_prepare ($dbc, $q)) {
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
// Get the number of rows returned:
$rows = mysqli_stmt_num_rows($stmt);
echo $rows;
mysqli_stmt_free_result($stmt);
mysqli_stmt_close($stmt);
}
You need to call execute() on your statement handle, right now you are only preparing the query.
$q = "SELECT name, address, contact FROM members";
$stmt = mysqli_prepare ($dbc, $q);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
// Get the number of rows returned:
$rows = mysqli_stmt_num_rows($stmt);
echo $rows;
i was concerned whether your table Members actually had records in it. Anyways try
$rows = mysqli_num_rows($stmt);
//or
$rows = mysql_num_rows($stmt);
This has worked out for me and has returned 5 as there were only 5 records in my table.

How to use mysqli_insert_id with prepared statements?

I have the following code and I'm getting crazy with calling an auto_increment id
$sql = "INSERT INTO tablename (x1, x2) VALUES(?,?)";
if($query = $db->prepare($sql)){
$query->bind_param('ss', $x1, $x2);
$query->execute();
$id = mysqli_insert_id($query);
For a reason I don't know why this is not working. I also tried
$id = mysqli_insert_id($sql);
And
$id = mysqli_insert_id();
I just decided to work with mysqli. Before that, I only used MySQL where I had no problem with
$id = mysql_insert_id();
You must pass the mysqli link to mysqli_insert_id(), not the query:
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$sql = "INSERT INTO tablename (x1, x2) VALUES(?,?)"
$result = mysqli_query($link, $sql);
$id = mysqli_insert_id($link);
or since you were using object oriented style:
// ...
$id = $mysqli->insert_id;
Probably something like
$query->commit(); OR $query->close();
It's best to stick to OOP style. It will cause you less confusion. In OOP style you only need to access a property on the object. For example:
$stmt = $db->prepare($sql);
$stmt->bind_param('ss', $x1, $x2);
$stmt->execute();
// Either one will work
$stmt->insert_id;
$db->insert_id;
If you want to use the procedural mysqli style then you have to remember that there are two functions. One if for the mysqli object and the other is for mysqli_stmt object. You need to pick either one of them, but you have to pass the right object to it.
// For mysqli_stmt object
mysqli_stmt_insert_id($stmt);
// For mysqli object
mysqli_insert_id($db);
$result = mysql_query($sql);
if(!$result) {
{
die('Error: ' . mysql_error());
} else {
echo "<p>Done!.</p>";
}
Try this and check the output...

Categories