I have this problem, when i am printing the second parameter from mysqli query it prints out the query to be performed but when i print the first parameter it prints nothing and when I perform the query it produces an error and it cannot insert the data into database. Here's my code:
$Insert_Patient_Data = "INSERT INTO patient_account(P_Password,P_Fname,P_Lname,P_Mname,P_Age,P_Gender,P_Email)
VALUES('$Encrypted_Password', '$Inputted_First_Name', '$Inputted_Last_Name', '$Inputted_Middle_Name', '$Inputted_Age', '$Inputted_Gender', '$Inputted_Email')";
$Patient_Query = mysqli_query($Connection, $Insert_Patient_Data);
if(!$Patient_Query)
echo "<script type = 'text/javascript'> alert('Error: Database Connection error. Please try again Later.') </script>";
else
echo "<script type = 'text/javascript'> alert('Succesfully Registered.') </script>";
I tried to print the second parameter which is $Insert_Patient_Data , it prints the query. there is nothing wrong in the output.
I tried to print the first paramter which is $Connection and it gives an error: Recoverable fatal error: Object of class MySQLi could not be converted to string
I tried to print the $Patient_Query but it prints nothing, even the second parameter (which is $Insert_Patient_Data) became null at this line.
At this time i tried to perform the $Patient_Query (Not printing it) and it goes to the if(!$Patient_Query) decision.
Question: Why it becomes a null? and what happens? and what is the solution on it? There are some queries on this page accessing the same table but they had no problem.
P.S. i checked the table name and column names from the database and they are all okay. I also included the System_Connector.php (Where the connection to database and the variable $connection is declared).
var_dump($Connection) will show you have a mysqli object, you cant echo objects!
Anyway, call mysqli_error($Connection) if it fails http://php.net/manual/en/mysqli.error.php
$Patient_Query = mysqli_query($Connection, $Insert_Patient_Data) or die(mysqli_error($Connection));
Or even:
if(!$Patient_Query = mysqli_query($Connection, $Insert_Patient_Data);)
//fail
else
// pass
Related
I am having a strange issue with mysqli_num_rows. Searching for this issue, I've only found people having issues where NULL is returned no matter what. I also checked the official documentation for the function, and it says it returns an integer of the number of rows returned by the query. Whenever my query returns 1 row (it never should return more), it behaves as I expect. When the query returns 0 rows, I expect the function to return 0, but it returns NULL. Why doesn't it return 0?
I know that my database connection is good and my query works correctly, because when I look for a record that's in the database, I get an integer back. I just can't figure out why this is returning NULL rather than 0.
function getArtistID($name) {
global $conn;
$query = "SELECT artist_id FROM artist WHERE artist_name LIKE '${name}'";
$result = mysqli_query($conn, $query);
if ($result->num_rows) {
$row = mysqli_fetch_assoc($result);
return $row['artist_id'];
} else {
return 0;
}
}
Here's some code that I used to reproduce a case where num_rows seems to be NULL:
<?php
error_reporting(E_ALL);
$conn = new mysqli('127.0.0.1', 'root', null, 'test');
$sql = "SELECT * FROM dual";
$result = $conn->query($sql);
if ($result === false) {
print "Error: {$conn->error}\n";
}
$n = $result->num_rows;
echo "Dump the num_rows property: ";
var_dump($n);
Output:
Error: No tables used
Notice: Trying to get property of non-object in /Users/bkarwin/Documents/SO/my.php on line 14
Dump the num_rows property: NULL
The notice is because it's invalid to access an object-oriented property of a variable that is not an object. This is a frequent source of confusion for PHP developers, and it's a byproduct of the fact that PHP is a loosely typed language, and functions like query() can return either a result object, or a boolean scalar.
The query() function actually returned a false as $result because of some error. In my code, I checked for this error, and you didn't.
When you run mysqli::query() or mysqli::prepare() or mysqli_stmt::execute(), you must check for error conditions every time.
Something about your query caused an error. It's up to you to check for the error and report it.
Update: I edited some text above to make the explanation better, but it might make some comments below seem out of place.
I just can't figure out why this is returning NULL rather than 0.
We can only guess without seeing the log output; but, it is likely the return value is null because it raised an error instead.
You need to ensure that errors are handled when calling a function, before attempting to use the return value.
I've tried to use the solutions presented in this question,
to no avail, so I used this:
$stat = "SELECT MAX(employee_id) FROM employees";
$querysult = intval($connection, $stat);
Where employee_id is an int(3) in the database table.
For some reason, the above code actually gets the values from the database, despite there not being a mysqli_query() in sight. But my question is about what I did immediately after, which was
echo "Id: " . $querysult;
and which output nothing but
Id:
and no number. I've also tried casting the number to a string, and concatenating it to an empty string before the echo statement.
For some reason, the above code actually gets the values from the database, despite there not being a mysqli_query() in sight
This of course is quite impossible, unless you are getting something from a previously executed query that uses the same variable names.
I think your main problem is that accessing the value of the query coded using just SELECT MAX(employee_id) will return a column with the name MAX(employee_id) and that is not a valid PHP variable name. So what you have to do is give that column another name that is a valid PHP variables name using this syntax SELECT MAX(employee_id) as max_empid which renames the column to max_empid
I am assuming nothing so I will also include a connection to the database in my answer. You will need to replace the my_user, my_password and my_db values, or ignore the connection if you have already dont that somewhere else. I have also used the Object Oriented approach to MYSQLI, if you are using the proceedural calls, you may have to amend the code accordingly
// connect to your database
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
// build query and use an alias for the `MAX(employee_id)`
// so you can easily use its name in the result set
$sql = "SELECT MAX(employee_id) as max_empid FROM employees";
// Now we must execute this query
$result = $mysqli->query($sql);
// Now we must chech that the query worked
if ( $result === FALSE ) {
echo sprintf( 'Query Failed: %s<br>%s', $sql, $mysqli->error);
exit;
}
// now we must read one of the rows from the result set
// produced by the ->query() command.
// In this case there of course there is only one result row
$row = $result->fetch_object();
echo 'Id: ' . $row->max_empid;
It may be because you are trying to convert a connection to an int value.
Try this
$connection = new mysqli();
$querysult =mysqli_query( $stat);
printf("Select returned %d.\n", $querysult->num_rows);
Going through a PHP MySQL tutorial and switching the PHP out for PDO; at any rate, my query is coming up blank.
$get_cat = $that->dbh->query("SELECT `cat_name`, `cat_desc` FROM `categories`");
if(isset($get_cat))
{
while($row = $get_cat->fetch(PDO::FETCH_ASSOC))
{
printf("
<tr>
<td>".$row['cat_name']." : ".$row['cat_desc']."</td>
</tr>
");
}
}
else
{
echo '<tr><td>return is false</td></tr>';
}
$That refers to:
include('db.php');
$that = new lib();
OLD:
So, why is my query blank? Before putting the die in it would return Boolean and give in an error in the loop with the die in it just comes up blank. The categories table has data in it and the page is refreshed on submission for new entries.
NEW:
Fatal error: Call to a member function fetch() on a non-object in C:\wamp\www\forum\create_category.php on line 36
Line 36 is the while loop line.
mysql_fetch_array is not PDO. You would need something like:
while($row = $get_cat->fetch(PDO::FETCH_ASSOC))
To get your rows.
Nor can you use mysql_error() to get the error. You could use for example $that->dbh->errorInfo() but you should look into exceptions for a more robust way to catch all errors.
Edit: You should check what the error is. Using isset is pointless as you have just assigned a value to it, so it will always be set.
You need to tell PDO to throw errors.
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$res = $that->dbh->query("SELECT cat_name, cat_desc FROM categories");
while($row = $res->fetch())
{
echo "<tr><td>$row[cat_name] : $row[cat_desc]</td></tr>\n";
}
run your code, read the error message and take appropriate action
Don't forget to add the first line into your db.php file, to make the setting permanent
Your query is incorrect -- is this what you're trying to do?
SELECT `categories`.`cat_name`, `categories`.`cat_desc` FROM `categories`
Hard to know without seeing you table structure.
Let's say you have a form with pre-populated data from your database, and you allow your users to make changes and save the form. If the user clicks the save button without making any changes, MySQL will not actually perform a write operation, and therefore the affected_rows will return 0.
I understand the behavior, but what is the best practice for determining if an update failed, other than checking for the number of affected_rows?
What is the best practice for differentiating between an update that actually failed, and one that "succeeded" but resulted in 0 affected_rows so that I can provide feedback to the user?
Just check if no errors occurred after execution of query.
If you use mysql, check mysql_error():
if (!mysql_error()) print 'all is fine';
Same for mysqli.
Variation 1:
mysql_query() or die('error');
Variation 2:
$conn = mysql_query();
if(!$conn) {//Error code here}
Variation 3:
try {
$conn = mysql_query();
if (!$conn) throw new Exception("mysql Error");
} catch(Exception $e) {
echo $e->getMessage();
}
[affected_rows()][1] is -1 if a query fails, not zero.
[1]: http://www.php.net/manual/en/function.mysql-affected-rows.php
It may return 0 if no changes were made to the row (same values), or if mysql didnt find a row to update. It will only return -1 due syntax erro
if the update "fails" due to syntax error, or other mysql will return an error code on the actual mysql query and affected_rows will return with yet another error.
Php for example:
$qry = mysql_query("update blah where IamaSyntaxerror,33");
if ($qry === FALSE) { echo "an error has occured"; }
else { mysql_affected_rows() == 0 means no updates occured
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?