As a part of a login system I need to check if the username exists in the database so I created a query that checks if the username the user entered already exists.
With mysql_result I check if the id is larger as null. If yes: user exists and if not the user doesn't exist. But here it goes wrong and wampserver gives me this error:
Warning: mysql_result() expects parameter 1 to be resource, object given in users.php on line 6
function user_exists($username){
global $user_db;
$username = sanitize($username);
$query = mysqli_query($user_db , "SELECT COUNT(`id`) FROM `users` WHERE `username` = '$username'");
$result = mysql_result($query, 0); //line 6
if(!$result){
return false;
}else{
return true;
}
}
and this is the code that calls that function:
if(user_exists('name') === true){
echo 'exists';
}
$user_db = mysqli_connect("localhost","root","","databaseName");
What did I try:
if I do this: mysqli_result($result,0,"id"); I get this error: Call to undefined function mysqli_result().
got this suggestion from this question
All the answers on questions like mine say that you should not use mysql
and mysqli both but only one of them but when I only use mysli I get the error like I told one paragraph above this one.
So can somebody tell me how to fix this.
You are mixing mysql and mysqli a bit. There is no function mysqli_result() in mysqli driver. However I found a solution to your problem. From comment in PHP documentation:
Converting an old project from using the mysql extension to the mysqli
extension, I found the most annoying change to be the lack of a
corresponding mysql_result function in mysqli. While mysql_result is a
generally terrible function, it was useful for fetching a single
result field value from a result set (for example, if looking up a
user's ID).
The behavior of mysql_result is approximated here, though you may want
to name it something other than mysqli_result so as to avoid thinking
it's an actual, built-in function.
The code:
<?php function mysqli_result($res, $row, $field=0) {
$res->data_seek($row);
$datarow = $res->fetch_array();
return $datarow[$field]; }
?>
Source: http://php.net/manual/en/class.mysqli-result.php
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'm trying to define a function to execute an Oracle query and set the mode for oci_fetch_array() dynamically with the string variable received. This is the function:
public function db_single_select($conn,$select,$table,$condition,$fetch_mods='') {
//A string should be sent to "$fetch_mods" with this format: mode1+mode2+etc...
//If a value is not passed to '$fetch_mods', it will be the default fetch mode
$sql = oci_parse($conn, "select $select from $table where $condition");
$sql_result = oci_execute($sql, OCI_DEFAULT);
if($sql_result){
if(empty($fetch_mods)) {
$res = oci_fetch_array($sql);
}
else{
$res = oci_fetch_array($sql, $fetch_mods);
}
}
else{
$res = FALSE;
}
oci_free_statement($sql);
return $res;
}
I call the function like this:
db_single_select($conn, $select, $table_name, $condition, 'OCI_ASSOC');
I get this Warning:
Warning: oci_fetch_array() expects parameter 2 to be long, string given in db_connect.php on line 61
I know that the second parameter (mode) for oci_fetch_array() should be numeric as it says so in the PHP documentation. http://www.php.net/manual/en/function.oci-fetch-array.php
The question is how to set the mode based on a variable received by the function??
Since you can have multiple modes by seperating them with a + sign like
$row = oci_fetch_array ($stid, OCI_ASSOC+OCI_RETURN_NULLS);
, is there an easy way to receive a string like OCI_ASSOC+OCI_RETURN_NULLS in the function and set the mode with that??
You seem to be misunderstanding what constants actually are. In the specific case of OCI_ASSOC (and other OCI constants) it represents a simple integer value. This can be demonstrated by the output of var_dump(OCI_ASSOC); which is int(1). Combining constants such as OCI_ASSOC+OCI_RETURN_NULLS is a simple addition operation with the result of int(5).
To make your function work you should simply pass the constants directly by removing the surrounding apostrophes:
db_single_select($conn, $select, $table_name, $condition, OCI_ASSOC);
SECURITY WARNING:
Your code is vulnerable to SQL Injection (also see what the PHP manual says about it). You should use parameter binding to mitigate the attack possibilities.
You have to be sure if the connection is succeeded or not.
check the return if it's resource value of $conn in your code.
wish this help you.
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 9 years ago.
I have links on my webpage like this: http://test.com/index.php?function=news&id=88
So whenever I put a ' after 88, I get the following error: Warning: mysql_fetch_row() expects parameter 1 to be resource, boolean given in ... line 588
So I read about mysql_real_escape_string(), but I'm getting the ID not posting and I have no clue how should I prevent getting this error.
function news()
{
$query = mysql_query("SELECT * FROM news WHERE id=".$_GET['id']."");
while($news = mysql_fetch_row($query))
{
...
}
}
The easy way is to cast the id to integer, if the id is an integer that is:
$id = (int)$_GET['id'];
But it's strongly recomended to use pdo or mysqli with prepared statements:
http://php.net/manual/en/book.pdo.php
http://php.net/manual/en/book.mysqli.php
You can do a redirect whenever mysql_fetch_row() don't return anything (i.e. because there is no id 89)
Something like:
if (!$row = mysql_fetch_row($result)) {
header(Your error page);
}
Warning: mysql_fetch_row() expects parameter 1 to be resource
This means the the $result = mysql_query(....); call you made before the mysql_fetch_row() failed and resulted FALSE instead of a Resource ( i.e. a handle to the query result );
Look at the query, post it if possible, that is where your problem is.
Your code assumes that the query was successful without checking. For debugging purposes, add an 'or die(mysql_error())' line to the end of the mysql_query() statement.
$query = mysql_query("SELECT * FROM news WHERE id=".$_GET['id']."") or die( mysql_query() );
For more robust error handling in production applications, check the value of $query and log an error if it is false.
if (false === $query ) {
// Log error and/or notify an administrator
}
else {
while($news = mysql_fetch_row($query)) ...
As pointed out in other answers, you should ensure that the value of the id parameter is an integer since your query assumes that it will be. You can do this by casting:
(int)$_GET['id']
or via more robust type checking
if ( !is_numeric( $_GET['id'] ) ) {
// Take appropriate action
}
else {
// Create and execute the query
Before anyone jumps on me, I have found a similar issue here, but unfortunately their answer does not seem to apply to my problem.
I have created a function called sqlReturn() in order to more easily produce an error (with standard output) should a query go wrong. The code is below:
function sqlResult($query)
{
return mysql_query($query)
or die("SQL Query: " . $query . "<br />SQL Error: " . mysql_error());
}
As you can see, it just outputs an error in the way I like, and it saves me a bit of effort in coding along the way. However, while this has been working in most cases (eg. situations where I use SELECT or INSERT), it is throwing the following error:
PHP Warning: mysql_fetch_array() expects parameter 1 to be resource,
boolean given in /var/www/login/login_submit.php on line 42
It is returning 1 instead of a resource. If, instead of calling that function (which is in a separate php file), I simply use the line of code in the same file without a return statement
(ie. $sqlResult = mysql_query($sqlQuery) or ... etc.), it returns a resource as normal.
In case it's relevant, my SQL query is also below:
$sqlQuery =
"SELECT userID, username, password, access_level
FROM users
WHERE username = '{$username}'
AND (password = '{$password_sha1}' OR password = '{$password_sha256}')";
Any input on this would be appreciated.
Thanks,
Paragon
Sneaky suspicion that binding rules are kicking in here. PHP may be seeing your function as
return (mysql_query(...)) or die(...);
and return before ever seeing the die(). Try rewriting like this
function sqlQuery(...) {
$result = mysql_query(...);
if ($result === FALSE) {
die(mysql_error(...));
}
return $result;
}
so there's no chance of any mis-parsing.
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?