I am trying to get both the results of my query and the row count wihtout having to make two trips the the DB if possible. I am using prepared statements in a procedural way. My code is as follows:
$dbd = mysqli_stmt_init($dbconnection);
if (mysqli_stmt_prepare($dbd, "SELECT * FROM Contacts WHERE First_Name = ?" )) {
mysqli_stmt_bind_param($dbd, "s", $val1);
if (!mysqli_stmt_execute($dbd)) {
echo "Execute Error: " . mysqli_error($dbconnection);
} else {
//do nothing
}
} else {
echo "Prep Error: " . mysqli_error($dbconnection);
}
$result = mysqli_stmt_get_result($dbd);
So the above code works just fine and returns my results. What I want to do now is get the row count using this same statement but i don't want to have to write a brand new prepared statement. If I writer a separate prepared statement and use store_results and num_rows I get the row count but that would force me to have to write an entire new block of code and trip to db. I am trying to do something as follows but It throws and error:
$dbd = mysqli_stmt_init($dbconnection);
if (mysqli_stmt_prepare($dbd, "SELECT * FROM Contacts WHERE First_Name = ?" )) {
mysqli_stmt_bind_param($dbd, "s", $val1);
if (!mysqli_stmt_execute($dbd)) {
echo "Execute Error: " . mysqli_error($dbconnection);
} else {
//do nothing
}
} else {
echo "Prep Error: " . mysqli_error($dbconnection);
}
$result = mysqli_stmt_get_result($dbd);
mysqli_stmt_store_result($dbd);
$rows = mysqli_stmt_num_rows($dbd);
The throws and error as if i can't run both get results and store results using the same prepared statement. Im simply trying to keep my code compact and reuse as much as possible. If i break the above out into two separat prepared statements it works fine, Im just wondering there is a way to just add a line or two to my existing statement and get the row count. Or do i have to write an entire new block of code with new stmt_init, stmt_prepare, bind_param, execute, etc...
I tried your code (and reformatted it a bit), but I can't get it to work when I use both store_result() and get_result(). I can only use store_result then bind_result().
So the alternative is to fetch all the rows and then count them:
Example:
$sql = "SELECT * FROM Contacts WHERE First_Name = ?";
$stmt = mysqli_stmt_init($dbconnection);
if (mysqli_stmt_prepare($stmt, $sql) === false) {
trigger_error("Prep Error: " . mysqli_error($dbconnection));
return 1;
}
if (mysqli_stmt_bind_param($stmt, "s", $val1) === false) {
trigger_error("Bind Error: " . mysqli_stmt_error($stmt));
return 1;
}
if (mysqli_stmt_execute($stmt) === false) {
trigger_error("Execute Error: " . mysqli_stmt_error($stmt));
return 1;
}
$result = mysqli_stmt_get_result($stmt);
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
$num_rows = count($rows);
print "$num_rows rows\n";
foreach ($rows as $row) {
print_r($row);
}
In my opinion, PDO is much easier:
$pdo = new PDO("mysql:host=127.0.0.1;dbname=test", "xxxx", "xxxxxxxx");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$sql = "SELECT * FROM Contacts WHERE First_Name = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$val1]);
$num_rows = $stmt->rowCount();
print "$num_rows rows\n";
while ($row = $stmt->fetch()) {
print_r($row);
}
Related
I am new to prepared statements. This function is not showing any output. What could the be problem?
function selectFwhere($id) {
$con = mysqli_connect('localhost','root','','car_rental');
$sql = mysqli_prepare($con,'SELECT * FROM `car_admin` WHERE admin_id = ?') or die("Unable to prepare statement: " . $con->error);
$sql->bind_param('i',$id);
$sql->execute();
$result = $sql->get_result();
while($row = $result->fetch_assoc() ){ echo " ".$row['admin_username']; }
$sql->close();
$con->close();
selectFwhere(1);
}
You need to move the line selectFwhere(1); outside the function body, after the closing }
I am trying to get the results from a query which should get multiple results and display them all on the page. However it is not displaying any of the content. My guess is a mistake in my syntax for me loop. But I am unsure.
//query to find comments about this map
$query = "
SELECT
user_id,
comment
FROM map_comments
WHERE
map_id = :mapID
";
//query parameters
$query_params = array(
':mapID' => $_SESSION['mapID']
);
try
{
//execute query
$statement = $db->prepare($query);
$result = $statement->execute($query_params);
//get all results
$comments = $result->fetchAll;
if($result === FALSE)
{
die(mysql_error()); // TODO: better error handling
}
}
catch(PDOException $e)
{
die("failed to find comments");
}
foreach($comments as &$comment)
{
echo $comment;
}
You need parentheses after a function to call it.
$comments = $result->fetchAll;
should be:
$comments = $statement->fetchAll();
Also, the check for if ($result == FALSE) should be before this line. And you can't use mysql_error() if you're using PDO, you should use $statement->errorInfo(). Or you should enable PDO::ERRMODE_EXCEPTION on the connection, and the catch block will be invoked. You should then use $db->errorInfo() in the error message that it prints.
This method is part of a larger class, and am trying to get it to return an array of objects containing the same classes. However, it doesn't seem to be entering the while loop, and I can't figure out why. Any suggestions?
The expected result would be an array of objects containing this data http://sqlfiddle.com/#!9/b6e23/1.
public static function getAllFacts($groupID)
{
$factTable = array();
$conn = new mysqli($GLOBALS['hostName'], $GLOBALS['userName'], $GLOBALS['password'], $GLOBALS['database']);
if ($conn->connect_error)
{
echo "Database connection error (source table)<br>";
}
$query = "SELECT factID, sourceID, factTXT, citationID, noteGroupID, factCreated, factsGroupID FROM facts WHERE factsGroupID = ?";
$stmt = $conn->prepare($query);
if ($stmt)
{
$stmt->bind_param("i", $groupID);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result(
$factID,
$sourceID,
$factTXT,
$citaitionID,
$noteGroupID,
$factCreated,
$factsGroupID
);
$row = 0;
while ($stmt->fetch())
{
$numRows = $stmt->num_rows;
echo "numRows: " . $numRows . "<br>";
$factTable[$row] = new self($factID, $sourceID, $factTxt, $citationTxt, $noteGroupID, $factCreated, $factsGroupID, $numRows);
$row++;
}
$stmt->close();
}
else
{
echo "Statement failed. (source table) <br>";
}
return $factTable;
}
How to check MySQL results are empty or not. If MySQL query results are empty then else condition should not be executed.
In case MySQL results in data there & in else condition my error my message is there but it is not showing any error message.
I have tried the following code but not showing any alert or echo message on the screen.
<?php
$sql = "select * from hall_search_data_1 where rent BETWEEN '".$_SESSION['amount1']."' AND '".$_SESSION['amount2']."'";
$res = mysql_query($sql);
if (!empty($res)) {
while ($row = mysql_fetch_row($res)) {
// here my data
}
} else {
echo "no results found";
}
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "id: " . $row["id"] . " - Name: " . $row["firstname"] . " " . $row["lastname"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Check number of rows
$result = mysqli_query($conn, $sql);
$rowcount=mysqli_num_rows($result);
if($rowcount > 0){
echo "Number of rows = " . $rowcount;
}
else
{
echo "no record found";
}
You can use mysql_num_rows to get count of number of rows returned from query.
if(mysqli_num_rows($res) > 0)
{
// rest of your stuff
}
else
{
echo "No records found.";
}
Note: mysql is deprecated instead use mysqli or PDO as seen above
Security Tip First of all stop using the mysql_* functions because they are not secure for production and later versions has stopped support for this API. So if accidentally you used those function in production then you can be in trouble.
It is not recommended to use the old mysql extension for new development, as it was deprecated in PHP 5.5.0 and was removed in PHP 7. A detailed feature comparison matrix is provided below. More Read
For your answer you have to only check no of rows is zero or not
Read this Post at php documentation with Example.
mysqli_num_rows
mysql_* API has been removed from PHP long time ago. To access the database you should use PDO. Checking if PDO has returned any results is actually pretty simple. Just fetch the results and if the array is empty then there was nothing returned from MySQL.
$stmt = $pdo->prepare('SELECT * FROM hall_search_data_1 WHERE rent BETWEEN ? AND ?');
$stmt->execute([$_SESSION['amount1'], $_SESSION['amount2']]);
$records = $stmt->fetchAll();
if ($records) {
foreach ($records as $row) {
// your logic
}
} else {
echo 'No records found!';
}
There is also mysqli library and if you are stuck using it you have to do a little more work, but the idea is the same. Fetch all results and if nothing was fetched then it means MySQL returned no rows.
$stmt = $mysqli->prepare('SELECT * FROM hall_search_data_1 WHERE rent BETWEEN ? AND ?');
$stmt->bind_param('ss', $_SESSION['amount1'], $_SESSION['amount2']);
$stmt->execute();
$records = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
if ($records) {
foreach ($records as $row) {
// your logic
}
} else {
echo 'No records found!';
}
You can use mysql_num_rows(); to check your query return rows or not
$sql = "select * from hall_search_data_1 where rent BETWEEN '".$_SESSION['amount1']."' AND '".$_SESSION['amount2']."'";
$res = mysql_query($sql);
$rows=mysql_num_rows($res);
if($rows>0)
{
echo "data return from query";
}else{
echo "data not return";
}
Note:- mysql is deprecated instead use mysqli or PDO
New to mySQL PDO. I have read other answers here and read tutorials and am finally taking the plunge. Problem is I cannot seem to output data. Hence, can someone assess my code to ensure it is correct? Also, is the system I am using to query the db efficient and clean and secure? thanks
$pdo --- the correct connection information is in this line but has been removed ---
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// SELECT sql query
try {
$thedate='2013-06-03';
$rotation=1;
$stmt = $pdo->prepare("SELECT * FROM sched_main_2013 WHERE thedate=:thedate AND rotation=:rotation");
$stmt->bindValue(':thedate', $thedate, PDO::PARAM_STR);
$stmt->bindValue(':rotation', $rotation, PDO::PARAM_INT);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
}
catch(PDOException $ex) {
echo $ex->getMessage();
}
while($rows = $stmt->fetch()) {
echo $rows['thedate'] . "\n";
echo $rows[assignedRad] . "\n";
echo $rows[rotation] . "\n";
}
// close the connection
$pdo = null;
This code outputs nothing. No errors. Nothing at all.
By the way, the table exists and the SELECT * FROM works fine when I manually run the mySQL statement, so data does exist with this query.
Try
while($rows = $stmt->fetch()) {
echo $rows['thedate'] . "\n";
echo $rows[assignedRad] . "\n";
echo $rows[rotation] . "\n";
}
To
while($rows = $stmt->fetch()) {
echo $rows['thedate'] . "\n";
echo $rows['assignedRad'] . "\n";
echo $rows['rotation'] . "\n";
}
Debug 01
Maybe you can try this to test whether you truly receive any data from database
print_r($stmt->fetchAll());
Instead of your while-loop
Debug 02
Try the simple query that you strongly believe there will be no SQL error for example:
SELECT * FROM sched_main_2013
Without any value binding.
Debug 03
Try another query with WHERE condition, but no binding
SELECT * FROM sched_main_2013 WHERE thedate='2013-06-03' AND rotation=1
You told that var_dump($row) gives you FALSE. The documentation says:
The return value of this function on success depends on the fetch type. In all cases, >FALSE is returned on failure.
Add the following line:
while($row = $stmt->fetch()) {
echo $row['thedate'] . "\n";
echo $row['assignedRad'] . "\n";
echo $row['rotation'] . "\n";
}
if($row === FALSE) {
var_dump($stmt->errorInfo());
die();
}
Further note: You originally named the return value of $stmt->fetch() $rows (plural) instead of $row. I'm not sure whether you know that the method will return a single row each time it is called.
What it have to be
$sql = "SELECT * FROM sched_main_2013 WHERE thedate=? AND rotation=?";
$data = array('2013-06-03', 1);
$stmt = $pdo->prepare($sql);
$stmt->execute($data);
$rows = $stmt->fetchAll();
var_dump($rows);
$sql = "SELECT * FROM sched_main_2013";
$data = array();
$stmt = $pdo->prepare($sql);
$stmt->execute(array());
$rows = $stmt->fetchAll();
var_dump($rows);
If second query returns the rows while first doesn't - there is no data found.
If both returns no rows - then it is caused by bad database design which is clearly seen from the table name, which should never have a postfix like this