I'm a bit of a noob but I am having trouble finding the answer to this question. I have two pieces of code and both work but I'm not sure why.
// Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Retrieve the score data from MySQL
$query = "SELECT * FROM table";
$result = mysqli_query($dbc,$query);
mysqli_close($dbc); // close db
In the instance above the connection is the first mysql_query parameter and then the sql query. This came from a book and isn't how the PHP manual defines it as far as I can see.
In the next example the sql is entered first, then the connection and I have to specifically use mysql_select_db. Why do they both work?
//db connection
$dbc = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$db_selected = mysql_select_db("database",$dbc); // select the db
$sql = "SELECT * from table"; // sql query
$result = mysql_query($sql, $dbc); // make query on db
mysql_close($dbc); //close the connection after data is acquired
Thanks in advance for any illumination you can supply.
Your first example
$result = mysqli_query($dbc,$query);
Is a function call to the newer mysqli library, http://www.php.net/manual/en/mysqli.query.php
Your second example
$result = mysql_query($sql, $dbc); // make query on db
Is a function call to the mysql library, http://www.php.net/manual/en/function.mysql-query.php
Both calls match the signature and order of arguments to those functions.
$result = mysqli_query($dbc,$query); // MySQLi (link, query)
$result = mysql_query($sql, $dbc); // MySQL (query, link)
You're using mysqli_query in the first example, and mysql_query in the second.
Two different function with two different parameter order, that's why I "love" PHP.
Because mysql_query() expects query as first parameter and mysqli_query() expects your query as 2nd.
mysqli_query
mysqli_query ( mysqli $link , string $query [, int $resultmode ] )
mysql_query
mysql_query ( string $query [, resource $link_identifier ] )
mysql_select_db() is required because mysql_connect() doesn't have database as parameter, instead of mysqli_connect().
The function mysql_select_db let you choose another db along your code without the need of 'another' new connection, using the same connection you started with mysql_connect.
Related
I'm migrating from PHP 5 to PHP 7, and I made a grep to get all mysql_query to change them to mysqli_query. The problem is, apparently the parametres changed using the procedural style.
mysql_query($query, $link_identifier)
mysqli_query($link_identifier, $query)
Even tho using the object oriented style they're still the same parametres.
Question is, will it work if I leave the parameters of mysqli_query as $query, $link thinking that the function is smart enough to detect which is which or I need to change them all to match the right parameters ?
Order of arguments isn't interchangeable.
Php.net mysqli_query.
Php.net mysql_query.
I also tested it.mysql_query
$link = mysql_connect("localhost","login","pass");
$db_selected = mysql_select_db('db', $link);
$sql = "SELECT * FROM table LIMIT 5";
$result = mysql_query($sql, $link);
while($row = mysql_fetch_array($result)) {
echo $row['col_name'];
}
mysql_close($link);
mysqli_query with with wrong order of arguments will produce: Warning: mysqli_query() expects parameter 1 to be mysqli, string given code here:
$link = mysqli_connect("localhost", "login", "pass", "db");
//arguments in wrong order
if ($result = mysqli_query("SELECT * FROM table LIMIT 5", $link)) {
while($row = mysqli_fetch_array($result)) {
echo $row['col_name'];
}
}
//produce
//Warning: mysqli_query() expects parameter 1 to be mysqli, string given in
mysqli_close($link);
I tried setting a variable like this: $test_id = mysql_insert_id($dbc); because I wanted to get the id of the last row inserted. I am able to connect to the database and insert the row but the next line (setting $test_id) it says this: supplied argument is not a valid MySQL-Link resource . Any ideas?
Here's the code:
$user_id = $_SESSION['user_id'];
$q = "INSERT INTO tests (user_id, title, subject, creation_date) VALUES ('$user_id', '$title', '$subj', NOW())"; //query to insert test details into tests table
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
$test_id = mysql_insert_id($dbc);
if (mysqli_affected_rows($dbc) == 1) {//if the query ran correctly and the test details were added to the database
$q = "INSERT INTO content (test_id, field1) VALUES ($test_id, '$content')"; //query to insert test content into content table
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
$dbc is defined like this:
$dbc = #mysqli_connect (DB_HOST, DB_USER, DB_PASS, DB_NAME);
From the comments:
Oh, I see now. You're mixing mysql_* with mysqli_* functions. Those are different libraries. They don't mix. Use mysqli_insert_id() instead.
You should put the link identifier (the output of mysql_connect(), not mysql_query())
mysql_insert_id implicitly calls SELECT LAST_INSERT_ID() which is session-specific.
Normally you can leave out that parameter; it will know that you have a database connection open. If you want to specify the connection, use the return value from mysql_connect:
$dbc = mysql_connect('localhost', 'mysql_user', 'mysql_password');
// later
echo mysql_insert_id($dbc);
Again, this is normally not necessary.
Also keep in mind that mysql_insert_id will only work after you've made an INSERT query where an index column with AUTO_INCREMENT was incremented. It will not return the latest ID that was inserted at some other time before the current session. For that you you could for example do:
SELECT MAX(id) FROM some_table;
The problem is that you're using a MySQLi resource in a MySQL function (note the missing i). There are 2 different extensions there. If you're using mysqli, don't switch to mysql. So just change that function to mysqli_insert_id($dbc);
Here is my error:
Warning: mysql_query() expects parameter 2 to be resource, null given...
This refers to line 23 of my code which is:
$result = mysql_query($sql, $connection)
My entire query code looks like this:
$query = "SELECT * from users WHERE userid='".intval( $_SESSION['SESS_USERID'] )."'";
$result = mysql_query($query, $connection)
or die ("Couldn't perform query $query <br />".mysql_error());
$row = mysql_fetch_array($result);
I don't have a clue what has happpened here. All I wanted to do was to have the value of the users 'fullname' displayed in the header section of my web page. So I am outputting this code immediately after to try and achieve this:
echo 'Hello '; echo $row['fullname'];
Before this change, I had it working perfectly, where the session variable of fullname was echoed $_SESSION['SESS_NAME']. However, because my user can update their information (including their name), I wanted the name displayed in the header to be updated accordingly, and not displaying the session value.
Your $connection variable is NULL that's what your error message is referring to.
Reason being is that you have not called mysql_connect. Once called it will assign you a resource where you can set it to the $connection variable, thus being non-null.
As an example:
$connection = mysql_connect('localhost', 'mysql_user', 'mysql_password');
// now $connection has a resource that you can pass to mysql_query
$query = "SELECT * from users WHERE userid='".
intval( $_SESSION['SESS_USERID'] )."'";
$result = mysql_query($query, $connection)
include the mysql connections on your class file, for example:
connections/mysql.php
<?
$hostname_MySQL = "localhost";
$database_MySQL = "database";
$username_MySQL = "user";
$password_MySQL = "password";
$MySQL = mysql_pconnect($hostname_MySQL, $username_MySQL, $password_MySQL) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_MySQL,$MySQL);
?>
class.php
<?
include "Connections/MySQL.php";
class utils {
public function myFunction()
{
global $MySQL;
$sql = "select * from table";
$rs = mysql_query($sql, $MySQL) or die(mysql_error());
$filas = mysql_fetch_assoc($rs);
$totalFilas = mysql_num_rows($rs);
...
}
}
?>
You have two ways of doing this, you need to use mysql_connect to connect to your database, you can pass this to mysql_query if you desire, if you don't pass anything to mysql_query PHP uses the last link opened from mysql_connect
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1";
$result = mysql_query($sql);
Have you connected to your database? If so please show this code too.
For now, just try removing the $connection variable, like this:
$result = mysql_query($query);
And see where that gets you.
$connection is assigned the value of the database connection resource id. You don't have that in your script, so the value of $connection is NULL, and that is why you are getting the error. You need to connect to the database before using mysql_query(). You should be okay after that.
You need to do:
$connection=mysql_connect('host','user','pass');
if($connection === false) {
echo "Error in connection mysql_error()";
}
I have a mysqli_query statement like so:
$result = mysqli_query($connection,$query)
I am wondering: If I call mysqli_query multiple times during the execution of a script, does it use the same connection to the db? Or is a new connection established each time?
Thanks,
It should use the same connection, providing you don't tell it to reconnect.
mysql_query() (which is different from mysqli_query() but should behave the same in this regard) always uses the last opened connection if one isn't provided.
So for this:
$connection1 = mysqli_connect('host1');
$query1 = mysqli_query('SELECT column1');
$query2 = mysqli_query('SELECT column2');
$connection2 = mysqli_connect('host2');
$query3 = mysqli_query('SELECT column3');
$query and $query2 will both run on the connection to host1, and $query3 will run on the connection to host2
Okay I have a piece of code that for some reason gives me the following errors.
Warning: mysqli_query() expects at least 2 parameters, 1 given in
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in
here is the code below.
$dbc = mysqli_query("SELECT * FROM sitename WHERE id='$user_id'");
while($row = mysqli_fetch_array($dbc)){
$state = $row["state"];
$city = $row["city"];
$zip = $row["zip"];
$bio_body = $row["bio_body"];
If you can please help me by giving me the correct code.
You need to include the database link parameter as well as the query you want to run. Like this:
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$dbc = mysqli_query($mysqli,"SELECT * FROM sitename WHERE id='$user_id'");
I don't see why it wouldn't work after that's fixed.
mysqli_query expects a link identifier from the database as the first argument, which is returned by mysqli_connect.
this causing the query to get a null result, which is causing the second error.
http://us3.php.net/manual/en/mysqli.query.php
http://us3.php.net/manual/en/mysqli.connect.php
From PHP builder:
Description
Procedural style: mixed mysqli_query (
mysqli link, string query [, int
resultmode] )
This basically means you are missing one parameter, the link you create when you open the database connection. Take a look at the following example:
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$dbc = mysqli_query($link, "SELECT * FROM sitename WHERE id='$user_id'");
mysqli_fetch_array doesn't work because the previous command failed.