This question already has answers here:
mysqli_query() expects at least 2 parameters, 1 given
(5 answers)
Closed 1 year ago.
Working on a login for admins on my webpage. I am following a tutorial that is kind of old, and I am trying to update it for MYSQLI. On his video, everything works perfect.. For me however..
if(isset($_POST['submit'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
if(empty($username) or empty($password)) {
echo "<p class='warn'>Oops!</p>";
} else {
$checklogin = mysqli_query(" SELECT id FROM admins WHERE username='$username' AND password='password' ");
if(mysqli_num_rows($checklogin) == 1){
echo "You can log in.";
} else {
echo "Oops";
}
}
}
and
Warning: mysqli_query() expects at least 2 parameters, 1 given in /opt/lampp/htdocs/WEBSITES/Site1/admin/login.php on line 29
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in /opt/lampp/htdocs/WEBSITES/Site1/admin/login.php on line 31
Errors about incorrect parameters can often be solved by looking up the manual for the function in question.
In this case, go to http://php.net/mysqli_query and you will see this function summary:
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
So the two parameters expected are the mysqli object representing the connection to the database (which you will get when you first connect), and then the string of SQL to run (which you are currently passing).
The second error is a consequence of the first: because you are not checking for errors, $checklogin doesn't represent a successful query result.
Incidentally, there are a few other problems you might want to look at here, if the tutorial doesn't go on to explain them:
md5 is not a secure method for hashing passwords. Take a look at this for a more secure solution, or at least use a more up to date hash function.
you are checking empty($password), but have already applied a hashing function, which will never return an empty string
you are wide open to SQL injection; see How can I prevent SQL injection in PHP?
Your call to mysqli_query() requires the first parameter to be your connection to the database, which would have been returned during mysqli_connect(). That is your first warning.
Since you didn't provide a connection to mysqli_query() the return value of $checkLogin equals null, this is where your second warning comes in. mysqli_num_rows() expects a result set from a successful query.
Here is your fix:
$connection = mysqli_connect("host", "user", "pass", "yourDB");
$result = mysqli_query($connection, "SELECT some, fields FROM YourTable WHERE something = 'this'");
Related
Need help with
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given
I'm trying to do a steamOpenID login button, but I get an error when it comes to my mysqli_query, it returns a boolean. Is it a problem with my database or in the code?
$url = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?
key=$_STEAMAPI&steamids=$matches[1]";
$json_object= file_get_contents($url);
$json_decoded = json_decode($json_object);
foreach ($json_decoded->response->players as $player)
{
$sql_fetch_id = "SELECT * FROM `SteamOpenID` WHERE `steamid`=$player->steamid";
$query_id = mysqli_query($db, $sql_fetch_id);
// This line triggers the warning
if(mysqli_num_rows($query_id) == 0){
$sql_steam = "INSERT INTO SteamOpenID (name, steamid, avatar) VALUES ('$player->personaname','$player->steamid','$player->avatar')";
mysqli_query($db,$sql_steam);
Firstly, mysql_query is a very old function and has been deprecated as it clearly says in the documentation.
Secondly, you don't bother to check if file_get_contents actually worked. This returns FALSE on failure. You should check the result using the strict equality comparison operator === (3 equal signs) like so:
$json_object= file_get_contents($url);
if ($json_object === FALSE) {
die("could not fetch the remote url");
}
Thirdly, you don't bother to check of the json_decode worked either. The docs say it will return NULL if the JSON cannot be decoded.
if (is_null($json_decoded)) {
die("JSON decoded as NULL");
}
You should also probably do some sanity checking on $json_decoded. But, assuming you get the array you want and assuming each player has a steamid property, it might just work.
I'd probably change your SQL definition to this:
$sql_fetch_id = "SELECT * FROM `SteamOpenID` WHERE `steamid`=" . mysql_real_escape_string($player->steamid);
You should always validate and/or escape input before you put it in your queries or you risk SQL injection.
And finally, we come to the problem at hand, which is that you don't bother to check the result of mysql_query before you just start using other functions on it. As the documentation says:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error. You should check what it returns before to make sure it didn't return false before you start running other functions on it.
$query_id = mysql_query($sql_fetch_id);
if (!$query_id) {
die('Invalid query: ' . mysql_error());
}
You'll probably find that your SQL has an error.
EDIT: I also just noticed that you are supplying two parameters to mysql_query. The first param you supply to that function should be your SQL query string. The code you provided also doesn't tell us where you defined $db. You should probably reverse those two parameters. Read the docs and you'll see that the first parameter is the query string and the second parameter is the link identifier that you got when you called mysql_connect. It's an optional parameter. If you don't supply it, the function will use the last connection opened using mysql_connect.
This question already has answers here:
Warning: mysqli_select_db() expects exactly 2 parameters, 1 given
(2 answers)
Closed 6 years ago.
Attempting to solve this issue. I'm trying to restore a extremely old version of Wordpress, back when it was known as B2, into a working state. After making a bunch of edits to the code in a attempt to get it working, I'm now getting this:
Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in /home/Redacted/public_html/b2-include/b2functions.php on line 31
Here's the segment of the code that's having issues:
<?php
/* functions... */
function get_currentuserinfo() { // a bit like get_userdata(), on steroids
global $HTTP_COOKIE_VARS,$user_login,$userdata,$user_level,$user_ID,$user_nickname,$user_email,$user_url,$user_pass_md5;
// *** retrieving user's data from cookies and db - no spoofing
$user_login = $HTTP_COOKIE_VARS["cafeloguser"];
$userdata = get_userdatabylogin($user_login);
$user_level = $userdata["user_level"];
$user_ID=$userdata["ID"];
$user_nickname=$userdata["user_nickname"];
$user_email=$userdata["user_email"];
$user_url=$userdata["user_url"];
$user_pass_md5=md5($userdata["user_pass"]);
$pref_usequicktags=$userdata["pref_usequicktags"];
$pref_postnavigator=$userdata["pref_postnavigator"];
$pref_showinactiveusers=$userdata["pref_showinactiveusers"];
$pref_textarearows=$userdata["pref_textarearows"];
$pref_confirm=$userdata["pref_confirm"];
$pref_usespellchecker=$userdata["pref_usespellchecker"];
// *** /retrieving
}
function dbconnect() {
global $connexion, $server, $loginsql, $passsql, $base;
$connexion = mysqli_connect($server,$loginsql,$passsql) or die("Couldn't connect! So sad :( <p>You should look into this!</p>");
$connexionbase = mysqli_select_db($base) or die("Couldn't connect! So sad :( <p>You should look into this!</p>");
return(($connexion && $connexionbase));
}
I am getting the error when I load the site at all. I can provide more code if necessary.
Posting as a community wiki. I don't want rep from this and there shouldn't.
$connexionbase = mysqli_select_db($base)
Just as the error states. You need to pass the db connection as the first argument:
$connexionbase = mysqli_select_db($connexion, $base)
Reference:
http://php.net/manual/en/mysqli.select-db.php
Example from the manual:
bool mysqli_select_db ( mysqli $link , string $dbname )
Sidenote:
return(($connexion && $connexionbase));
TBH, I've never seen this type of syntax for a return. Far as I know, you can return only once or using an array.
Pulled from this answer https://stackoverflow.com/a/3815243/1415724
You can only return one value. But you can use an array that itself contains the other two values:
return array($uid, $sid);
Instead of going through all that trouble, just use the 4 parameters:
$connexion = mysqli_connect($server,$loginsql,$passsql, $base)
as per the manual:
http://php.net/manual/en/function.mysqli-connect.php
then return with and if it's really needed.
return $connexion;
Plus, why are you intending to use MD5 to store passwords with? That hashing function is no longer considered safe to use.
You're better off using password_hash().
http://php.net/manual/en/function.password-hash.php
This is the 21st century after all.
and $HTTP_COOKIE_VARS, that's deprecated.
http://php.net/manual/en/reserved.variables.cookies.php
I've no idea why you're using that code or where you got it from.
You need to pass the database name into your mysqli_select_db() function. Right now you're passing the connection improperly, you need to have that second parameter or it doesn't know what to do. Try updating it to this:
$connexionbase = mysqli_select_db(connexion, $base) ...
I got the warning:
Warning: mysqli_query() expects parameter 1 to be mysqli, string given in (...) on line 6
My code is here:
<?php
require_once 'conn.php';
$sql = "SELECT user_id, access_lvl, name FROM cms_users ";
$result = mysqli_query($sql, $conn);
It's exactly as the error states as you're passing arguments to mysqli_query() incorrectly. Assuming $conn is your mysqli connection generated at some point by new mysqli() it should be:
$result = mysqli_query( $conn,$sql) or trigger_error(mysqli_error($conn)));
The way you were calling it you were passing a string, $sql as the first argument.
I was having this this problem but after swiping
$result = mysqli_query($sql, $conn) to $result = mysqli_query( $conn,$sql)
I manage to solve this error
I am 3 years too late but all you need to do is swap the parameters of mysqli_query()
$result = mysqli_query($conn, $sql)
I have the same error, although the $result = mysqli_query($conn, $sql) is the correct way around.
I var_dump() the $conn object and it is a set object at the time I run the query, but still returns a 'string given' error.
I was accessing the $conn object after being parsed into a function that I was using it with, in the same way I've done throughout the whole project without error.
Re-declaring the $conn object inside the function, instead of passing it into the function stopped the errors, although this behaviour doesn't occur anywhere else in my project. This isn't an ideal solution either.
To note: I'm using a .env for local development, which causes no issues and helps with deployment locally/remotely via .git.
After many hours, I honestly believe there is a PHP bug here, I'm using 7.3.0, but occurred in 7.2.5 as well as I'm definitely parsing it a db connection object, not a string.
Just posting this for information purposes, in case anyone else runs into it. Thanks.
PS. Passwords shouldn't be stored in the database in plain text and is a major security concern. If the author hasn't adjusted this yet (I know it's an old post), it's important to read:
Secure hash and salt for PHP passwords
I've searched the site for an answer but couldn't find any answer for my specific problem that worked.
I have two files, the first one is my index.php of-course, the second is my functions.php file, which obviously contains the functions, I made this function:
function sql_get($lang, $tabler, $rower){
if ($lang == "heb") {
$result = mysql_query("SELECT * FROM %s WHERE id = 0",
mysql_real_escape_string($tabler));
$row = mysql_fetch_array($result);
return $row['$rower'];
}
else if ($lang == "rus") {
$result = mysql_query("SELECT * FROM %s WHERE id = 0",
mysql_real_escape_string($tabler));
$row = mysql_fetch_array($result);
return $row['$rower'];
}
this code supposed to get an information about the language (from a get, it gets it, it's all fine with that), the sql table and the specific row from this table where the id is 0.
and return the information from the row inserted.
My warnings and errors when the language is "heb":
Warning: mysql_query() expects parameter 2 to be resource, string given in /home/elenbyin/public_html/elenby.co.il/vadim/functions.php on line 16
Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in /home/elenbyin/public_html/elenby.co.il/vadim/functions.php on line 17
and when the language is "rus":
Warning: mysql_query() expects parameter 2 to be resource, string given in /home/elenbyin/public_html/elenby.co.il/vadim/functions.php on line 23
Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in /home/elenbyin/public_html/elenby.co.il/vadim/functions.php on line 24
the function call in the index.php file looks like that:
I will be thankful for the people who will try to help and especially for those who will help me.
Thanks A lot!
Firstly, you haven't connected to the database inside your function. If you've opened your database somewhere then you can get away with this with mysql, but you shouldn't.
Secondly, you're passing your variable as a second parameter to mysql_query(), but mysql_query() expects the query to be complete as the first parameter, and the second parameter should be the connection resource tht connects to the database, which you haven't got.
From the structure of the query it looks like you intend to use sprintf() to create it.
This should create the query for you, assuming you have opend a databse connection:
$query = sprintf("SELECT * FROM %s WHERE id = 0",
mysql_real_escape_string($tabler));
$result = mysql_query($query) or die(mysql_error());
Note: mysql is deprecated. You shouldn't use it. Use mysqli or PDO instead. You'll need to be more rigorous about passing in your database connecions if you use mysqli.
As Amal suggested - better not use mysql_* functions cause not only they're deprecated but also vulnerable to sql-injection.
That said, in order to fix your code you should do:
$table = mysql_real_escape_string($tabler);
$sql = "SELECT * FROM $table WHERE id = 0";
$link=mysql_connect('host','user','pass');
$result = mysql_query($sql, $link);
...
as the second (and optional) parameter of mysql_query should be a resource - not a string!
This question already has answers here:
mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource
(31 answers)
Closed 9 years ago.
Ok, so I know the question about 'why am I getting this warning with mysql_fetch_array...' has been asked several times, my problem is all the accepted answers state that the reasons the server is spitting this warning out is because the query itself is incorrect...this is not the case with me.
Here is the code below:
$dbhost = "host";
$dbuser = "user";
$dbpass = "pass";
$dbname= "db";
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($dbname) or die ('<META HTTP-EQUIV="Refresh" CONTENT="0;URL=Failed.php?dberror=1">');
$token = mysql_escape_string($_GET['token']);
$query = "SELECT * FROM newuser WHERE token='$token'";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)) {
do stuff...
}
Everything within the 'while' statement is being executed just fine - it makes some changes to the DB which I can validate is happening. More importantly, the query never spits out any error details. I've tried testing for cases where $result===false and asking for error info but it won't return anything then either. From what I can tell, the query string is fine and is not failing.
What am I doing wrong here? Could there any other reason why PHP doesn't like my While parameters other than the SQL statement is bad (which again, I'm convinced it's not bad)?
Also, I know I should be using mysqli/PDO....I plan to switch over to that in the near future, but I'm pulling my hair out just trying to make this work and I have no idea why it won't. It's more of a personal thing at this point...
Thanks for your help, and let me know if you need any additional info. (PHP Version 5.3)
Here is an echo of the query string ($query):
SELECT * FROM newuser WHERE token='6e194f2db1223015f404e92d35265a1b'
And here is a var_dump of the query results ($result): resource(3) of type (mysql result)
$query = "SELECT * FROM newuser WHERE token='$token'";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)) {
do stuff...
}
If the die statement is not executed, $result is OK when you enter the while loop. The problem then is probably that you use $result for a query inside the loop as well, eventually leading to it being set to false.
So for now i can say that the problem is not the mysql_escape_string nether the using of mysql at all neither access privilege from user name and password and what i want to tell you is to test the $result and if it is a resource proceed with your while block like this
if(is_resource($result))
{
while($row = mysql_fetch_array($result))
{//process your code here}
}
and tell me if the code has been also executed :)
The query is not correct according to mysql_. The error you're receiving is telling you that $result is boolean (false).
Where is $token coming from? You best stop using mysql_ functions and use a prepared statement and a bound parameter.
your escape is wrong try this
$token = mysql_real_escape_string($_GET['token']);
instead of $token = mysql_escape_string($_GET['token']);
This extension is deprecated as of PHP 5.5.0, and will be removed in the future.
http://php.net/manual/en/function.mysql-real-escape-string.php