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
Related
i want to connect two mysql databases one is located in localhost and other one is located in a server
here is what i have done so far and i am not getting either error or data
<?php
$con=mysql_connect('120.247.201.8:3306','root','root');
$con1=mysql_connect('localhost','root','');
//mysql_connect('localhost','root','');
if(!$con){
die('Try Again');
}
if(!$con1){
die('Try Again');
}
mysql_select_db("iot",$con1);
mysql_select_db("lora_gateway",$con);
$result =mysql_query("SELECT lora_gateway.`server_log`.`created_at`, lora_gateway.`server_log`.`temperature`FROM iot.`device` inner JOIN `lora_gateway`.`server_log` on `lora_gateway`.`server_log`.`gateway_Id` = `iot`.`device`.`gatewayId` where iot.`device`.`deviceId`='23' ORDER BY lora_gateway.`server_log`.`created_at` desc");
$num= mysql_num_rows($result);
print_r($num);
?>
This is a solution for multiple servers, connections and DBs.
Two or more MySQL 5 db servers
Two or more locations (local and/or anything else)
Two or more different databases
Two or more tables and fields
Tested and Works fine :-)
//Define your database connections and select your database want to use. In this example I use two connections and two DBs. But you can use more than two.
<?php
//MySQL Server 1
$dbhost1 = "127.0.0.1";
$dbuser1 = "dbuser1";
$dbpassword1 = "dbpass1";
$db1 = "database1";
$connection1 = mysql_connect($dbhost1,$dbuser1,$dbpassword1) or die (mysql_error());
mysql_select_db($db1,$connection1);
//MySQL Server 2
$dbhost2 = "xxx.xxx.xxx.xxx";
$dbuser2 = "dbuser2";
$dbpassword2 = "dbpass2";
$db2 = "database2";
$connection2 = mysql_connect($dbhost2,$dbuser2,$dbpassword2) or die (mysql_error());
mysql_select_db($db2,$connection2);
//The SQL statement
$sql =" SELECT database1.tablename1.fieldname1 AS field1, database2.tablename2.fieldname2 AS field2 FROM database1.tablename1,database2.tablename2";
//Execute query and collect results in $results
$results = mysql_query($sql);
//Print result until end of records
while($rows = mysql_fetch_array($results)){
print $rows["field1"]." | ".$rows["field2"]."<br>";
}
?>
First of all, try to accustom yourself to using PDO or at least the mysqli_ functions. It's the future. :)
mysql_query's second parameter, the connection link, is optional. If omitted, it uses the last connection opened with mysql_connect. (See php.net Documentation)
Ergo, always use $con or $con1 as 2nd parameter in order to use the correct connection.
Then, provided that your queries are correct, it should work as expected.
what about to add connection to mysql_query() ?
$result = mysql_query("SELECT lora_gateway.`server_log`.... desc", $con);
session_start();
$user=$_SESSION['username'];
$con=mysqli_connect("$host","$username","$password","$db_name");
$sql1="SELECT UserID FROM User WHERE username='$user'";
$query=mysqli_query($con,$sql1);
echo $query;
Im not sure what's the problem with this, I've tried searching around here and tried different ways of writing the syntax and checking for errors in parameter but still no output for the command. What am i missing here?
UPDATE
$sql1="SELECT UserID FROM User WHERE username='$user'";
$query=mysqli_query($sql1,$con);
$row=mysqli_fetch_array($query);
$uid=$row[0];
echo $uid;
As answered by the others, I tried doing this. There is still no output or an output of 0 was given. Where if I tried the query in sql, it shows the right one.
UPDATE 2
It tried the var_dump() command and it returns NULL. Does that mean it can't read the database?
mysqli_query gives no output. A successfully query returns a resource. You have to handle the resource with mysqli_fetch_object, mysqli_fetch_assoc or mysqli_fetch_array.
Also you gave $con parameter before $sql1 which is wrong. You have to put the connection first, then the query variable.
Example:
<?php
session_start();
$user = $_SESSION['username'];
$con = mysqli_connect("$host", "$username", "$password", "$db_name");
$sql1 = "SELECT UserID FROM User WHERE username='$user'";
$query = mysqli_query($con, $sql1);
$fetch = mysqli_fetch_assoc($query);
var_dump($fetch);
?>
$query will be a "Resource". You can use for example $result = mysqli_fetch_array($query); and then echo $result[0];May there's another way, but that's a simple one!
I was able to do some workaround with my problem using mysql syntax. Still not able to determine the problem with mysqli but able to finished my task. Thanks for answering guys.
I am trying to get the top 10 items from a table:
<?php
include DBConnect.php;
$dbname = 'Telejoke';
mysql_select_db($dbname);
$query = "SELECT * FROM jokes LIMIT 10";
$data = mysql_query($query) or die('Error, insert query failed');
mysql_close($conn);
$info = mysql_fetch_array( $data );
?>
The PHP script keeps executing the die part saying that my query insert failed.
UPDATE:
The error is No connection could be made because the target machine actively refused it.
UPDATE 2:
I think the user I connect to DB is not authorized to use the SELECT command. This would cause the preceding error?
In db connection.php you must use a user name with password who is allowed to do operations on db.
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.
$db_user="root";
$db_host="localhost";
$db_password="root";
$db_name = "fayer";
$conn = mysqli_connect($db_host,$db_user,$db_password,$db_name) or die ("couldn't connect to server");
// perform query
$query = 'SELECT * FROM posts';
$result = mysqli_query($conn, $query) or die ("Couldn't execute query.");
// use returned data
while($row = mysqli_fetch_assoc($result))
{
echo $row['title'];
}
I get in the browser: "mysql problem".
Help!
UPDATE
I have echoed the query. It shows SELECT * FROM posts and when I query manually it gets the rows.
I think it has something to do with mysqli. I think i should use mysql. Do u think I have incompatibility problems with mysqli?
i have echoed it. it shows SELECT * FROM posts. and when i query manually it gets the rows.
i think it has something to do with mysqli. i think i should use mysql. do u think i have incompatibility problems with mysqli?
You have empty WHERE clause. Remove it or add a search condition.
Change
$result = mysqli_query($conn, $query) or die ("Couldn't execute query.");
to
$result = mysqli_query($conn, $query) or die ("Couldn't execute query because: " . mysqli_error());
and you will know why the query is failing. Rule of thumb: Whenever you have a failed query, print it out and run it through phpmyadmin or some other raw-query executor and you will discover very quickly what the problem is.