This question already has answers here:
mysqli_query() expects at least 2 parameters, 1 given
(5 answers)
Closed 9 years ago.
Im trying to convert a project of mine from mysql to mysqli but it seems to give me a error
Warning: mysqli_query() expects at least 2 parameters, 1
this is my database connection
$mysqli = new mysqli();
$mysqli->connect('localhost', 'root', '', 'myscript');
this is the query
$sql = mysqli_query("SELECT * FROM settings WHERE id='1'") or die (mysqli_error());
$results = mysqli_fetch_array($sql);
if anyone can tell me how to fix this error i will be grateful. thanks in advance.
You can try performing your query using Object oriented PHP way instead of mixing and matching Object oriented PHP and regular PHP:
$mysqli = new mysqli();
$mysqli->connect('localhost', 'root', '', 'myscript');
if($result = $mysqli->query("SELECT * FROM settings WHERE id='1'")){
//DO STUFF
$result->close();
}else{
printf("Error: %s\n", $mysqli->error);
}
Please, do not convert a project of yours from mysql to mysqli.
Convert it to PDO.
Mysqli is good only for the silly examples from beginner's manual - it will make your life harder as you progress.
So, instead of mysqli just use PDO.
It's almost the same:
$opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$pdo = new PDO('mysql:dbname=myscript;host=localhost','root','', $opt);
$stm = $pdo->prepare("SELECT * FROM settings WHERE id=?");
$stm->execute(array(1));
$data = $stm->fetch();
Note parameretized query support - the main reason for such a move between drivers - which already used in this code.
Even in such small examples PDO is better. Way better. And with more complex ones mysqli will become totally unusable while PDO would be the same - quite ugly but at least feasible.
Related
This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 3 years ago.
$Createdby=$_SESSION['adminlog'];
$total =$_POST['total'];
$due =$_POST['due'];
$date =$_POST['issedate'];
$invoiceno =$_POST['invno'];
$CmpnyName =$_POST['CmpnyName'];
$itemdetails =$_POST['item_details'];
$itemname =$_POST['itemname'];
$amtpaid =$_POST['paid'];
$query = "UPDATE billdata SET Total='$total' Due='$due' WHERE InvoiceNo=$invoiceno";
$result = mysql_query($query);
This is the code I am using to get HTML values to variable and update particular invoice number with new data.
First off, never use the deprecated mysql_* API.
Switch to either PDO or mysqli, both have prepared statements, which would make your code a tad bit more safe when it comes to SQL-Injections (which your code is very open for).
When a query fails, the mysql_error() global function will return the latest mysql error.
The easiest way to get information about a failing query is by adding or die(mysql_error()); after the query execution.
Example with your code:
$result = mysql_query($query) or die(mysql_error());
This will report your error and stop execute the script.
Your sql code is slightly wrong (as RST mentions), you are missing a comma between the values you are trying to set.
Using mysqli and prepared statements, your code could look something like:
// Using the mysqli object oriented style.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'username', 'password', 'database');
// Prepare the statement.
$statement = $mysqli->prepare('UPDATE billdata SET Total=?, Due=? WHERE InvoiceNo=?');
// The question marks is placeholders for the input that will be added in a while.
// Bind your parameters (ssi tells mysqli what type of params it is, s = string, i = int).
$statement->bind_param('ssi', $total, $due, $invoceno);
// Execute the statement.
$statement->execute();
// Cleanup.
$statement->close();
$mysqli->close();
$query = "UPDATE billdata SET Total='$total', Due='$due' WHERE InvoiceNo=$invoiceno";
There should be a comma between the sets of values.
It is not a good idea to use the value from $_POST() as they are, better perform some validation checks.
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
This question already has answers here:
How to change mysql to mysqli?
(12 answers)
Closed 1 year ago.
Php is not going to promote some MySql functions in upcoming days.
There is some examples about cleaning deprecated functions in PHP manual. But for example; when i replace mysql_query with mysqli_query in code below doesn't work. Also Notepad++ treats them like functions which is defined by myself. All examples are using OOP in PHP manual. I need an example without using object orianted programing.
Can someone tell me that how can i clean my code from deprecated mysql functions?
function db_connect_select()
{
$connection = #mysql_connect(MYSQL_HOSTNAME, USERNAME_SELECT, PASSWORD);
if (!$connection)
{
return false;
}
if (!mysql_select_db(DATABASE))
{
return false;
}
mysql_query("SET NAMES UTF8");
return $connection;
}
function db_result_to_array($result)
{
$res_array = array();
for ($count = 0; $row = mysql_fetch_array($result); $count++)
{
$res_array[$count] = $row;
}
return $res_array;
}
function select_top_tags()
{
$connection = db_connect_select();
$query = 'SELECT * FROM top_tags ORDER BY tag_name ASC';
$result = db_result_to_array(mysql_query($query));
if(mysql_ping($connection))
{
mysql_close($connection);
}
return $result;
}
It will just make no sense.
A mere mechanical replacement will do no good.
You have to understand that it is not old functions themselves, but old ways of using them is discouraged.
So, if you want to keep your current code as is - just keep it.
A red box in the manual is not that scary, and the version in which these functions are actually would raise a deprecated-level error is not out yet.
So, you have a 3-4 years ahead, before you will encounter whatever inconvenience. And even then to turn off deprecated-level errors is a matter of one runtime setting.
But if you want to write the better code - you have to use OOP way with PDO (and I can assure you that OOP is not that scaring. Although it require some knowledge when writing, it is very easy to use a ready made class. The only difference from familiar functions is a little -> thing. Not a big deal)
So, here you go:
function db_connect_select()
{
$dsn = 'mysql:host='.MYSQL_HOSTNAME.';dbname='.DATABASE.';charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
return new PDO($dsn,USERNAME_SELECT, PASSWORD, $opt);
}
function db_result_to_array($query,)
{
// not needed with PDO
}
function select_top_tags()
{
global $pdo;
$query = 'SELECT * FROM top_tags ORDER BY tag_name ASC';
$stm = $pdo->prepare($query);
$stm->execute();
return $stm->fetchAll();
}
usage:
$pdo = db_connect_select(); // somewhere in a bootstrap file
$tags = select_top_tags();
mysqli_* functions are not drop-in replacement for mysql_* functions. They are used in different way and simple replacement will not work. There are many tutorials on the Internet describing how to use mysqli_* functions in PHP, e.g. this one.
I think you should carefully read the manual section on migrating because it specifically talks about the (minor) differences between both extensions.
Some examples:
// no select_db, give db to _connect call
$connection = #mysqli_connect(MYSQL_HOSTNAME,USERNAME_SELECT,PASSWORD,DATABASE);
// need to give the connection parameter to mysqli_query
mysqli_query($connection,"SET NAMES UTF8");
and so on
As others already said, this procedural interface is mostly offered for convenience and to ease the transition. You should at the same time invest some time in mastering the more modern concepts used in the newer db interfaces - I'd strongly suggest you have a look at PDO, presently by far the best database API for PHP.
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 2 years ago.
I am getting the above warning when I try to run this code:
$mysqli=new mysqli("localhost", "***", "***","***") or die(mysql_error());
function checklogin($username, $password){
global $mysqli;
$result = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$result->bind_param("s", $username);
$result->execute();
if($result != false){
$dbArray=mysql_fetch_array($result);
You are mixing mysql and mysqli calls in your code. Use mysqli_fetch_array instead of mysql_fetch_array.
You are mixing mysqli and traditional mysql commands.
Use $result->fetch_array().
You're using two different sets of functions... mysqli and mysql.
I think you want to use the fetch_assoc() method.
Check out http://php.net/manual/en/book.mysqli.php
I would like to know how to use the common mysql_* stuff. I don't take to make SO a mess and make a question for each one, so I just put up this question with a small list:
num_rows
fetch_array
set_charset
fetch_row
This is the functions you use to normal mysql_* queries, what are the PDO´s functions equals to these?
And how can you INSERT INTO, UPDATE and DELETE
The only thing I know and tested right now is connect to the db + selecting like this:
$conn = new PDO("mysql:host=$host;dbname=$db",$user,$pass);
$sql = "SELECT id FROM users";
$q = $conn->query($sql) or die("failed!");
What I expect for an answer is either links to each function and attributes
(num_rows, fetch_array, insert into, update, etc..) or direct answers to them.
$q = $conn->query($sql) or die("failed!");
Don't do that. Use:
$conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
Then you'll get an exception if something goes wrong with the query.
have a look at the documentation: http://php.net/manual/en/book.pdo.php
Its all in there