update mysql_num_rows to new Mysqli standard: mysqli_stmt_num_rows - php

I have a PHP page with some Mysqli that I am attempting to convert from MySql. I think I've converted most of it correctly, but I am getting the following error message when I try to execute the code (below):
Connection was OK!
Warning: mysqli_stmt_num_rows() expects parameter 1 to be mysqli_stmt, object given in /quantityremaining5.php on line 25
9999
I'm a bit new to this, so please be gentle - what is that I'm doing wrong? thanks!
<?php
include 'quantitytest_config.php';
// Create connection to MySQL
$link = mysqli_connect($hostname, $username, $password);
// Check connection
if (mysqli_connect_errno($link))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else { echo "Connection was OK!\n";}
//select a database to work with
$selected = mysqli_select_db($link, "grace59_countdown");
// or die("Could not select countdown");
// use if TWO SEPARATE columns for date and time
//execute the SQL query and return records
$result = mysqli_query($link,
"SELECT items
FROM cases
WHERE datetime<=NOW()
Limit 1 ");
if(mysqli_stmt_num_rows($result) == 0){
echo "9999";
} else {
//fetch tha data from the database
while ($row = mysqli_fetch_array($result)) {
echo "Quantity:".$row{'items'}."<br>";
}
}
//close the connection
mysqli_close($link);
?>

Use mysqli_num_rows($result) or $result->num_rows. As the name indicates, mysqli_stmt_num_rows() is intended to be used with a mysqli_stmt object (as returned by mysqli_prepare()).
See the documentation.

Related

Simple MySQL call to select an integer at a specific key not working?

I have this PHP:
<?php
$client_ip = $_SERVER['REMOTE_ADDR'];
$connection = new mysqli("localhost", "MyNotSoSecretUsername", "MySuperSecretPassword", "MyNotSoSecretDatabaseName");
if ($connection->connect_error) {
die("Connection failed: " . $Connection->connect_error);
}
$check_emails_sent_query = "SELECT `emails` FROM `email-ips` WHERE `ip`='11.111.111.111'";
$check_emails_sent_result = $connection->query($check_emails_sent_query);
echo $check_emails_sent_result;
?>
This is a small piece of a much larger function on my site. This snippet is simply intended to get the value of the "emails" column (Which is an int column if that makes a difference) of my table where the IP matches the client's IP.
I added a fake entry for 11.111.111.111 in my database, and used the exact same query on PHPmyAdmin's SQL console. I got a result on the PHPmyAdmin console, but nothing is echoed here.
I have also checked that the connection is good, as you can see in my code. Additionally, I pasted another query from another part of my function, which retrieved its data just fine.
AS stupid or obvious as it may be, I can't seem to figure out why this particular query out of almost twenty won't retrieve its data?
Mysqli query() returns and object. Using the object:
<?php
$client_ip = $_SERVER['REMOTE_ADDR'];
$connection = new mysqli("localhost", "MyNotSoSecretUsername", "MySuperSecretPassword", "MyNotSoSecretDatabaseName");
if ($connection->connect_error)
{
die("Connection failed: " . $Connection->connect_error);
}
$check_emails_sent_query = "SELECT `emails` FROM `email-ips` WHERE `ip`='11.111.111.111'";
if ($check_emails_sent_result = $connection->query($check_emails_sent_query))
{
while($obj = $check_emails_sent_result->fetch_object())
{
$echo $obj->emails;
}
}
?>
You could use fetch_row() instead of fetch_object().
Documentation for the object is here:
http://php.net/manual/en/class.mysqli-result.php
mysqli_query()
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or
EXPLAIN queries mysqli_query() will return a mysqli_result object. For
other successful queries mysqli_query() will return TRUE.
You can get your email by using
if ($result = $connection->query($check_emails_sent_query)) {
while ($row = $result->fetch_row()) {
printf ("%s (%s)\n", $row[0]);
}
}

Outputting contents of database mysqli

Hi I know this is a little general but its something I cant seem to work out by reading online.
Im trying to connnect to a database using php / mysqli using a wamp server and a database which is local host on php admin.
No matter what I try i keep getting the error Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given when i try to output the contents of the database.
the code im using is:
if (isset($_POST["submit"]))
{
$con = mysqli_connect("localhost");
if ($con == true)
{
echo "Database connection established";
}
else
{
die("Unable to connect to database");
}
$result = mysqli_query($con,"SELECT *");
while($row = mysqli_fetch_array($result))
{
echo $row['login'];
}
}
I will be good if you have a look at the standard mysqli_connect here
I will dont seem to see where you have selected any data base before attempting to dump it contents.
<?php
//set up basic connection :
$con = mysqli_connect("host","user","passw","db") or die("Error " . mysqli_error($con));
?>
Following this basic standard will also help you know where prob is.
you have to select from table . or mysqli dont know what table are you selecting from.
change this
$result = mysqli_query($con,"SELECT *");
to
$result = mysqli_query($con,"SELECT * FROM table_name ");
table_name is the name of your table
and your connection is tottally wrong.
use this
$con = mysqli_connect("hostname","username","password","database_name");
you have to learn here how to connect and use mysqli

Simple SQL & PHP query failing

I haven't used PHP or SQL in a while, and can't seem to figure out why this query is failing. Probsbly going to be something silly :).
<php?
$dbconn = mysql_connect("localhost","xxx","xxx");
if (!$dbconn)
{
die('Error connecting to DB!');
}
if (! #mysql_select_db('rdrkictj_rsvp') )
{
die(mysql_error());
}
if(isset($_GET['id'])){
$ID = $_GET['id'];
$stockcount = $_GET['stockcount'] - 1;
}
else
die(mysql_error());
mysqli_query($dbconn,'UPDATE products SET stockcount = "5" WHERE id = "1"');
mysqli_close($dbconn);
?>
I receive the following errors:
Warning: mysqli_query() expects parameter 1 to be mysqli, resource
given in /home/rdrkictj/public_html/test/buyit.php on line 19
Warning: mysqli_close() expects parameter 1 to be mysqli, resource
given in /home/rdrkictj/public_html/test/buyit.php on line 21
Any advice would be greatly appreciated.
<php? should be <?php, also you're mixing mysql functions with mysqli functions. Choose one of them (mysqli). So, change: he
mysql_connect("localhost","xxx","xxx");
to the mysqli equivalent:
mysqli_connect("localhost","xxx","xxx");
Also change mysql_error() to mysqli_error(),
and finally change:
#mysql_select_db
to:
#mysqli_select_db
OK so that is what happens when you mix two tutorial together -_-
Thanks to both respondents. The following code works:
$con=mysqli_connect("localhost","xxx","xxx","xxx");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,'UPDATE products SET stockcount = "5" WHERE id = "1"');
mysqli_close($con);
Use either mysqli or mysql (mysqli is recommended)
For example:
$dbconn = mysql_connect("localhost","xxx","xxx");
should be
$dbconn = mysqli_connect("localhost","xxx","xxx");
Same for others as well
Full Code:
<?php
$dbconn = mysqli_connect("localhost","xxx","xxx") or die('Error connecting to server');
if (! #mysqli_select_db($dbconn, 'rdrkictj_rsvp') )
{
die(mysqli_error($dbconn));
}
if(isset($_GET['id'])){
$ID = $_GET['id'];
$stockcount = $_GET['stockcount'] - 1;
}
else
die(mysqli_error($dbconn));
mysqli_query($dbconn,'UPDATE products SET stockcount = "5" WHERE id = "1"');
mysqli_close($dbconn);
?>

How to print the value of a single cell using MySQL and PHP?

This returns a blank page:
<?php
$con=mysqli_connect("xxx.x.xx.x","user","password","db");
// check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT column FROM table WHERE id=1");
print $result;
mysqli_close($con);
?>
And this returns data:
<?php
$con=mysqli_connect("xxx.x.xx.x","user","password","db");
// check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM table");
while($row = mysqli_fetch_array($result))
{
echo $row['column_1'] . " " . $row['column_2'];
echo "<br>";
}
mysqli_close($con);
?>
What is wrong with the first block of code that prevents it returning any data?
http://php.net/manual/en/mysqli.query.php
tells me that mysqli_query returns a mysqli_query object. Not a primitive value like string or int.
The exact line that says this is:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or
EXPLAIN queries mysqli_query() will return a mysqli_result object. For
other successful queries mysqli_query() will return TRUE.
Hence the first block does not work because the first block assumes the value in the column is automatically returned.
In fact, if you used the same SELECT column from table where id=1, you still have to use the while loop to extract the values because it is STILL a mysqli_result object you are getting back.
By while loop I mean this:
while($row = mysqli_fetch_array($result))
{
echo $row['column_1'];
echo "<br>";
}
I hope this answers your question.

Error calling MySQL stored procedure through PHP

I'm trying to call a stored procedure from MySQL and get back the two OUT parameters (#eset and #leng). I would like to echo out these two parameters back to JavaScript where I have an XMLHttpRequest waiting for the results.
I'm getting this error :
Strict standards: mysqli::next_result(): There is no next result set.
Here's my code:
<?php
//get the q parameter from URL
$q=$_GET["q"];
$eset= "";
$length= 0;
// Opens a connection to a MySQL server
$db= new mysqli('localhost', 'db_name', 'pass');
if (!$db) { die('Not connected : ' . mysql_error());}
// Set the active MySQL database
$db_selected = $db->select_db('db_name');
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$db->multi_query( "CALL mst2($q, #eset, #leng);SELECT #eset as eset;SELECT #leng as length" );
$db->next_result(); // flush the null RS from the call
$eset=$db->store_result(); // get the RS containing the id
//echo $eset->fetch_object()->eset, "\n";
$length= $db->store_result();
//echo $length->fetch_object()->leng, "\n";
$response= $eset.$length;
//$eset->free();
//$length->free();
//$response=str_shuffle($q);
//output the response
echo $response;
?>
I'm assuming the first argument of your stored procedure is VARCHAR, so the first problem is that you are passing the $q variable without quotes in the query. It should be like this:
$db->multi_query("CALL mst2('$q', #eset, #leng); SELECT #eset as eset; SELECT #leng as length");
Also, you don't need to make two SELECT calls, do it only once:
SELECT #eset AS eset, #leng AS leng;
Needless to say that user inputs should never be trusted. You should use prepared statements:
if (($stmt = $db->prepare("CALL mst2(?, #eset, #leng)"))) {
$stmt->bind_param("s", $q);
$stmt->execute();
$stmt->close();
if (($res = $db->query("SELECT #eset AS eset, #leng AS leng"))) {
list($eset, $leng) = $res->fetch_array();
$result = $eset.$length;
echo $result;
$res->free();
}
}

Categories