mysqli::query() expects parameter 2 to be long, string given - php

I am in the middle of creating a custom shopping cart and I', building a query that begins with retrieving a session_id I just saved into the carts table. I know this value was saved, and I run this query at the mysql command line and it returns just what I need BUT I am not getting the value into the $cart_id. There are other INSERT queries above and below this point in the script so I know I'm connecting to the db just fine.
//Get cart id
$cart_id_select_q = "SELECT c.id FROM carts AS c WHERE c.user_session_id='$uid'";
$cart_id = $mysqli->query($conn, $cart_id_select_q);
echo "<pre>Debug: $cart_id_select_q</pre>";
if ( !$cart_id ) {
printf("error: %s\n", mysqli_error($conn));
}
else {
echo 'get session id from cart: execute success';
print_r($cart_id);
var_dump($cart_id);
}
I'm also on a VPS server with errors suppressed not I'm not getting a mysqli_error to display in the browser but I am getting the following 2 warnings in my error_log.
[29-Jul-2011 09:29:24] PHP Warning: mysqli::query() expects parameter 2 to be long, string given in /home/sopadmin/public_html/dev/cart.php on line 89
[29-Jul-2011 09:29:24] PHP Warning: mysqli_error() expects parameter 1 to be mysqli, null given in /home/sopadmin/public_html/dev/cart.php on line 92
I've also tried to use mysqli_num_rows() and fetch_assoc() but none have helped. the $cart_id remains null and I don't know how to retrieve the mysql error in this server configuration. Posting here is a last resort after toying with it all night.
I should note, I am just starting to really use the new mysqli extension and I'm also beginning to code in a more OO way. But I'm usually starting out coding procedurally and then creating classes when I have the design laid out. But that's just a comment on my experience level, what I don't understand is why this query is not returning a vlue inside my script.

When using object oriented mysqli API, you do not need (in fact you can't) pass a connection as the first argument.
This: $cart_id = $mysqli->query($conn, $cart_id_select_q);
should be: $cart_id = $mysqli->query($cart_id_select_q);
And this: printf("error: %s\n", mysqli_error($conn));
should be: printf("error: %s\n", mysqli->error);
I've no idea what $conn is (looks like a string), but it surely is not a MySQLi connection object.

Simple example to avoid such failure:
/* Select queries return a resultset */
$result = $mysqli->query("SELECT Name FROM City LIMIT 10");
if (!is_null($result)) {
printf("Select returned %d rows.\n", $result->num_rows);
/* free result set */
$result->close();
} else {
error_log("Mysql query failed" . $mysqli->error);
}

Related

Unexpected PDO "General error 2050" depending on configuration

I have some code where variable $query is supposed to hold different PDOStatement objects, one replaced by another:
$query = $conn->prepare("select * from ... ");
$query->execute();
while ($tmp=$query->fetch(PDO::FETCH_ASSOC)) {
...;
}
//unset($query);
$query = $conn->query("select * from ... ");
while ($tmp=$query->fetch(PDO::FETCH_ASSOC)) {
....;
}
With such code I get "SQLSTATE[HY000]: General error: 2050" from PDO on the line with the last fetch. But if I uncomment line with "unset" - it starts working correctly.
Any idea of what could it be?
PS Without using unset, it also works with PDO::ATTR_EMULATE_PREPARES = true
UPD
Here is error code description from MySQL site:
Error: 2050 (CR_FETCH_CANCELED)
Message: Row retrieval was canceled by mysql_stmt_close() call
in some php versions error 2050 happen because you must empty the var that holds the object with the result of the query
see https://stackoverflow.com/a/36631355/2613863
in Matt Cavanagh commet

Error Query PHP after migrate to mysql database

I have execute query using PHP which previously executed on mssql server database . Now with the same table and data. I using mysql database to execute my query. But error happen. Any suggestion for my query below in order to can execute using mysql database :
$year = mysql_query("SELECT * FROM education_year ORDER BY id DESC");
if (isset($_GET['year'])){
$educationyear= mysql_fetch_array(mysql_query("SELECT * FROM educationyear WHERE year='{$_GET['year']}'"));
}else {$educationyear = mysql_fetch_array($year);}
$kode['KODE'] = mysql_fetch_array(mysql_query("SELECT KODE FROM educationyear WHERE year='$educationyear'"));
$result = mysql_query("SELECT * FROM Province");
while($row = mysql_fetch_array($result))
{
$xd = mysql_fetch_array(mysql_query("SELECT COUNT (*) AS total FROM child WHERE id_province='{$row['province_code']}' AND education='A'
AND educationyear='{$educationyear['KODE']}'"));
}
Error message like below :
Notice: Array to string conversion in C:\xampp\htdocs\xy\demo.php on line 19
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\xy\demo.php on line 20 .
Its line when execute $xd query.
There are a few problems with your code
1st: When you use an array within double-quoted string, do not quote the array key. Change
"...WHERE year='{$_GET['year']}..."
"...WHERE id_province='{$row['province_code']}'..."
To:
"...WHERE year='{$_GET[year]}..."
"...WHERE id_province='{$row[province_code]}'..."
2nd: The design pattern below is not good:
mysql_fetch_array(mysql_query("SELECT...")
You're taking the result of mysql_query and feeding it directly to mysql_fetch_array. This works as long as the query succeeds and returns a resource. If the query fails, it will return FALSE and mysql_fetch_array will trigger the error you see:
mysql_fetch_array() expects parameter 1 to be resource, boolean given
Instead, make sure there is no error before proceeding
$result = mysql_query("SELECT...")
if($result===false){
//Query failed get error from mysql_error($link).
//$link is the result of mysql_connect
}
else{
//now it's safe to fetch results
$record = mysql_fetch_array($result);
}
3rd: do not use mysql_ functions. They have been abandoned for years and have been removed from the most recent version of PHP. Switch to MySQLi or PDO
4th: learn about prepared statements. You're using user supplied input directly in your query ($_GET['year']) and this makes you vulnerable to SQL injection.

php warning: mysqli_close() expects parameter 1 to be mysqli

I am attempting a connection to a sql db via php and keep getting an error I can't figure out. I can connect with another debug scripts with no errors. I get my connection and pull my data but pulls an error at the end.
$con=mysqli_connect("localhost","username","password","dbname");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT * FROM Locations";
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
}
// Close connections
mysqli_close($result);
mysqli_close($con);
?>
Brings this out
[{"Name":"Apple","Address":"1 Infinity Loop Cupertino, CA","Latitude":"37.331741","Longitude":"-122.030333"},{"Name":"Googleplex","Address":"1600 Amphitheatre Pkwy, Mountain View, CA","Latitude":"37.421999","Longitude":"-122.083954"}]
Warning: mysqli_close() expects parameter 1 to be mysqli, object given in /home/jfletch/public_html/appone/connect.php on line 36
mysqli_close($result);
The line above is incorrect. You only need to call mysqli_close() once (if at all since, as pointed out in the comments, the connection is closed at the end of the execution of your script) and the parameter should be your link identifier, not your query resource.
Remove it.
Traditionally we FREE the result, and CLOSE the connection. It looks like both those lines were copied from the same source during a copy/paste.
So the first mysqli_close does have a bad parameter.
You want mysqli_free_result($result); there instead.
Leaving aside that it is supposedly not necessary if the script ends. It cannot hurt. There may be a great many connections before the script ends if you do not re-use connections.

PDO::exec() blocking further query from working

I'm trying to implement pagination using PHP. I found that calling exec to the connected database prevents the further query calls from working.
The piece of code at hand:
<?php
// Pagination logic
//Here we count the number of results
$query = "SELECT COUNT(*) as num FROM gig";
$total_pages = $db->exec($query);
$total_pages = $total_pages[num];
?>
After it if I try to use a query such as:
<?php>
foreach ($db->query("SELECT sname, start, venue FROM gig WHERE start = '0000-00-00 00:00:00'") as $a) {
$row="<tr><td>$a[sname]</td><td>To be announced</td><td>$a[venue]</td></tr>\n";
print $row;
}
?>
it returns
Warning: Invalid argument supplied for foreach()
As soon as the first code block is removed, the query works fine. When I check the value of $total_pages, it's 0, so something must be going wrong along the way. As far as I know, I use it in the same way as the query(which works on its own), so is there any reason why it doesn't work?
The PDO is initialized in the following way:
try {
$db = new PDO("mysql:dbname=$db_name;host=$db_server", $db_user, $db_pw);
} catch (PDOException $e) {
die('Connection failed: ' . $e->getMessage());
}
session_start();
From Manual
PDO::exec() does not return results from a SELECT statement. For a
SELECT statement that you only need to issue once during your program,
consider issuing PDO::query(). For a statement that you need to issue
multiple times, prepare a PDOStatement object with PDO::prepare() and
issue the statement with PDOStatement::execute().
Used a function of the STATEMENT object had after using querying to count the rows instead of exec:
$dbq = $db->query("SELECT * FROM gig");
$rows = $dbq->rowCount();
About the latter code block not working because of the exec failing - it seems to just be the way php queries work, if one fails, all fail. The foreach() error is for the object it's provided is not an array, for it failed.

PHP Error - Login Script

I am creating a new login script/members directory.
I am creating it from scratch without any frameworks (advice on this matter would also be appreciated).
The situation:
// Look up the username and password in the database
$query = "SELECT admin_id, username FROM admin WHERE adminname = '$admin_user' AND password = SHA1('$admin_pass')";
$data = mysqli_query($dbc, $query);
if (mysqli_num_rows($data) == 1) {
This bit of code keeps giving me an error (the last line in particular):
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in /home8/craighoo/public_html/employees/security/dir_admin.php on line 20
When echoing the query I get:
SELECT admin_id, adminname FROM admin WHERE adminname = 'admin' AND password = SHA1('password')
EDIT:
Thanks to everyone. The problem was in my Database column names and the column names I was referencing.
Your query execution is failing. When that happens mysqli_query returns false (boolean value) and when is passed to mysqli_num_rows, you get this error.
Print the query just before executing and check for correctness.
Considering that mysqli_query returns false on failure, and that $data is a boolean, here, I suppose there is an error occuring during the execution of your SQL query.
You could try using mysqli_error to find out what this error is :
$data = mysqli_query($dbc, $query);
if ($data !== false) {
// Do whatever you want with $data
if (mysqli_num_rows($data) == 1) {
//
}
} else {
echo mysqli_error($dbc);
die;
}
Note : echoing the error message and dying, like I did here, is OK while developping your script ; but you should not do that in production.
Instead, in production, you should :
Log the error to a file
Display a nice message to the user
When you have a critical query, it's best to add a die to it like so:
mysqli_query($dbc, $query) or die('Critical error on line #'. __LINE__ .' when attempting to login ...<br>'. mysql_error());
Have you tried running that same query manually thru phpmyadmin or the console? What result do you get?

Categories