PHP mysql_query inside FOR only works first loop - php

I´m trying to update some different registers in a mysql database sending the commands from a FOR loop in php, but the query is only done the 1st loop. Here´s the code:
$conexion = mysql_connect($hostname, $user, $pass) or die ("Error establishing connection with the Database");
mysql_select_db($db,$conexion) or die("Error selecting the Database");
$j=0;
for ($i=0;$i<count($notifs);$i++){
$sql="UPDATE tef SET notif='$notifs[$i]' WHERE sn_rec='$unsersn_recs[$j]';";
echo $sql."<br>";
$res=mysql_query($sql, $conexion) or die (mysql_error());
$j++;
}
mysql_close($conexion);
The query text is correctly done (the echo shows the different lines created), but the changes in the database are done only in the 1st loop (1st query) and I don´t receive any error. What may I be missing?
Thanks in advance!

This is wonderful example where you should use prepared statements.
I give you an example which is also secure against SQL injections.
$mysqli = new mysqli($hostname, $user, $pass, $db);
if (mysqli_connect_errno()) {
die("Error establishing connection!");
}
$stmt = $mysqli->prepare("UPDATE tef SET notif=? WHERE sn_rec=?");
$j=0;
for ($i=0;$i<count($notifs);$i++) {
$stmt->bind_param('ii', $notifs[$i], $unsersn_recs[$j]);
$stmt->execute();
if(!empty($stmt->error)) echo $stmt->error;
$j++;
}
$stmt->close();
$mysqli->close();
Hint: If notif or sn_rec are varchar/text types, just replace the 'i' with a 's' in bind_param().

Related

Executing mysqli insert query then immediately selecting ID of new row

I've been spending a couple of hours trying to write mysqli queries to insert a new row in a database (with a primary key ID) and then select the ID of the new row. My code as it currently is:
<?php
include('connectionData.php');
$conn = mysqli_connect($server, $user, $pass, $dbname, $port)
or die('Connection error');
if(isset($_POST['submit'])) {
$pnum = $_POST['pnum'];
$phone_insert_text = "INSERT INTO `voterdatabase`.`phone` (`pnum`) VALUES (?)";
$phone_insert_query = $conn->prepare($phone_insert_text);
$phone_insert_query->bind_param('s', $pnum);
$phone_insert_query->execute();
$phone_select_text = "SELECT phone_id FROM voterdatabase.phone WHERE pnum=?";
$phone_select_query = $conn->prepare($phone_select_text);
$phone_select_query->bind_param('s', $pnum);
$phone_select_query->execute();
$phone_select_query->bind_result($phone_id);
echo $phone_id;
?>
$phone_insert_query executes without issue. But $phone_select_query doesn't appear to run at all, as echo $phone_id; has no effect. What might be going on here? I'm able to run the query directly in MySQLWorkbench.
Note that I previously tried doing this in one query using SELECT LAST_INSERT_ID();, but mysqli fails to execute any query containing that.
Please try this
$lastInsertID= mysqli_insert_id($conn);
Use insert_id property:
<?php
include('connectionData.php');
$conn = mysqli_connect($server, $user, $pass, $dbname, $port)
or die('Connection error');
if(isset($_POST['submit'])) {
$pnum = $_POST['pnum'];
$phone_insert_text = "INSERT INTO `voterdatabase`.`phone` (`pnum`) VALUES (?)";
$phone_insert_query = $conn->prepare($phone_insert_text);
$phone_insert_query->bind_param('s', $pnum);
$phone_insert_query->execute();
$phone_id = $conn->insert_id;
echo $phone_id;
?>
If you wish to be able to use the available functions to get the last inserted id, like mysqli_insert_id(), your table must have an AUTO_INCREMENT column. If not you will not get the id.
Also, even if you have the required columns, this will require two calls. To get around this, what you could do is something like create a stored procedure to do your insert for you and return the inserted id from the procedure.

how to connect more than two databases i.e (3 Databases) in php [duplicate]

I have information spread out across a few databases and want to put all the information onto one webpage using PHP. I was wondering how I can connect to multiple databases on a single PHP webpage.
I know how to connect to a single database using:
$dbh = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
However, can I just use multiple "mysql_connect" commands to open the other databases, and how would PHP know what database I want the information pulled from if I do have multiple databases connected.
Warning : mysql_xx functions are deprecated since php 5.5 and removed since php 7.0 (see http://php.net/manual/intro.mysql.php), use mysqli_xx functions or see the answer below from #Troelskn
You can make multiple calls to mysql_connect(), but if the parameters are the same you need to pass true for the '$new_link' (fourth) parameter, otherwise the same connection is reused. For example:
$dbh1 = mysql_connect($hostname, $username, $password);
$dbh2 = mysql_connect($hostname, $username, $password, true);
mysql_select_db('database1', $dbh1);
mysql_select_db('database2', $dbh2);
Then to query database 1 pass the first link identifier:
mysql_query('select * from tablename', $dbh1);
and for database 2 pass the second:
mysql_query('select * from tablename', $dbh2);
If you do not pass a link identifier then the last connection created is used (in this case the one represented by $dbh2) e.g.:
mysql_query('select * from tablename');
Other options
If the MySQL user has access to both databases and they are on the same host (i.e. both DBs are accessible from the same connection) you could:
Keep one connection open and call mysql_select_db() to swap between as necessary. I am not sure this is a clean solution and you could end up querying the wrong database.
Specify the database name when you reference tables within your queries (e.g. SELECT * FROM database2.tablename). This is likely to be a pain to implement.
Also please read troelskn's answer because that is a better approach if you are able to use PDO rather than the older extensions.
If you use PHP5 (And you should, given that PHP4 has been deprecated), you should use PDO, since this is slowly becoming the new standard. One (very) important benefit of PDO, is that it supports bound parameters, which makes for much more secure code.
You would connect through PDO, like this:
try {
$db = new PDO('mysql:dbname=databasename;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
echo 'Connection failed: ' . $ex->getMessage();
}
(Of course replace databasename, username and password above)
You can then query the database like this:
$result = $db->query("select * from tablename");
foreach ($result as $row) {
echo $row['foo'] . "\n";
}
Or, if you have variables:
$stmt = $db->prepare("select * from tablename where id = :id");
$stmt->execute(array(':id' => 42));
$row = $stmt->fetch();
If you need multiple connections open at once, you can simply create multiple instances of PDO:
try {
$db1 = new PDO('mysql:dbname=databas1;host=127.0.0.1', 'username', 'password');
$db2 = new PDO('mysql:dbname=databas2;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
echo 'Connection failed: ' . $ex->getMessage();
}
I just made my life simple:
CREATE VIEW another_table AS SELECT * FROM another_database.another_table;
hope it is helpful... cheers...
Instead of mysql_connect use mysqli_connect.
mysqli is provide a functionality for connect multiple database at a time.
$Db1 = new mysqli($hostname,$username,$password,$db_name1);
// this is connection 1 for DB 1
$Db2 = new mysqli($hostname,$username,$password,$db_name2);
// this is connection 2 for DB 2
Try below code:
$conn = mysql_connect("hostname","username","password");
mysql_select_db("db1",$conn);
mysql_select_db("db2",$conn);
$query1 = "SELECT * FROM db1.table";
$query2 = "SELECT * FROM db2.table";
You can fetch data of above query from both database as below
$rs = mysql_query($query1);
while($row = mysql_fetch_assoc($rs)) {
$data1[] = $row;
}
$rs = mysql_query($query2);
while($row = mysql_fetch_assoc($rs)) {
$data2[] = $row;
}
print_r($data1);
print_r($data2);
$dbh1 = mysql_connect($hostname, $username, $password);
$dbh2 = mysql_connect($hostname, $username, $password, true);
mysql_select_db('database1', $dbh1);
mysql_select_db('database2',$dbh2);
mysql_query('select * from tablename', $dbh1);
mysql_query('select * from tablename', $dbh2);
This is the most obvious solution that I use but just remember, if the username / password for both the database is exactly same in the same host, this solution will always be using the first connection. So don't be confused that this is not working in such case. What you need to do is, create 2 different users for the 2 databases and it will work.
Unless you really need to have more than one instance of a PDO object in play, consider the following:
$con = new PDO('mysql:host=localhost', $username, $password,
array(PDO::ATTR_PERSISTENT => true));
Notice the absence of dbname= in the construction arguments.
When you connect to MySQL via a terminal or other tool, the database name is not needed off the bat. You can switch between databases by using the USE dbname statement via the PDO::exec() method.
$con->exec("USE someDatabase");
$con->exec("USE anotherDatabase");
Of course you may want to wrap this in a catch try statement.
You might be able to use MySQLi syntax, which would allow you to handle it better.
Define the database connections, then whenever you want to query one of the database, specify the right connection.
E.g.:
$Db1 = new mysqli('$DB_HOST','USERNAME','PASSWORD'); // 1st database connection
$Db2 = new mysqli('$DB_HOST','USERNAME','PASSWORD'); // 2nd database connection
Then to query them on the same page, use something like:
$query = $Db1->query("select * from tablename")
$query2 = $Db2->query("select * from tablename")
die("$Db1->error");
Changing to MySQLi in this way will help you.
You don't actually need select_db. You can send a query to two databases at the same time. First, give a grant to DB1 to select from DB2 by GRANT select ON DB2.* TO DB1#localhost;. Then, FLUSH PRIVILEGES;. Finally, you are able to do 'multiple-database query' like SELECT DB1.TABLE1.id, DB2.TABLE1.username FROM DB1,DB2 etc. (Don't forget that you need 'root' access to use grant command)
if you are using mysqli and have two db_connection file. like
first one is
define('HOST','localhost');
define('USER','user');
define('PASS','passs');
define('**DB1**','database_name1');
$connMitra = new mysqli(HOST, USER, PASS, **DB1**);
second one is
define('HOST','localhost');
define('USER','user');
define('PASS','passs');
define(**'DB2**','database_name1');
$connMitra = new mysqli(HOST, USER, PASS, **DB2**);
SO just change the name of parameter pass in mysqli like DB1 and DB2.
if you pass same parameter in mysqli suppose DB1 in both file then second database will no connect any more. So remember when you use two or more connection pass different parameter name in mysqli function
<?php
// Sapan Mohanty
// Skype:sapan.mohannty
//***********************************
$oldData = mysql_connect('localhost', 'DBUSER', 'DBPASS');
echo mysql_error();
$NewData = mysql_connect('localhost', 'DBUSER', 'DBPASS');
echo mysql_error();
mysql_select_db('OLDDBNAME', $oldData );
mysql_select_db('NEWDBNAME', $NewData );
$getAllTablesName = "SELECT table_name FROM information_schema.tables WHERE table_type = 'base table'";
$getAllTablesNameExe = mysql_query($getAllTablesName);
//echo mysql_error();
while ($dataTableName = mysql_fetch_object($getAllTablesNameExe)) {
$oldDataCount = mysql_query('select count(*) as noOfRecord from ' . $dataTableName->table_name, $oldData);
$oldDataCountResult = mysql_fetch_object($oldDataCount);
$newDataCount = mysql_query('select count(*) as noOfRecord from ' . $dataTableName->table_name, $NewData);
$newDataCountResult = mysql_fetch_object($newDataCount);
if ( $oldDataCountResult->noOfRecord != $newDataCountResult->noOfRecord ) {
echo "<br/><b>" . $dataTableName->table_name . "</b>";
echo " | Old: " . $oldDataCountResult->noOfRecord;
echo " | New: " . $newDataCountResult->noOfRecord;
if ($oldDataCountResult->noOfRecord < $newDataCountResult->noOfRecord) {
echo " | <font color='green'>*</font>";
} else {
echo " | <font color='red'>*</font>";
}
echo "<br/>----------------------------------------";
}
}
?>

Open an SQL connection just once - mysqli_query

I used
mysqli_connect("infos in here");
at the top of my page, and tried to use
mysqli_query("INSERT INTO and other info here");
When I do that, I get this error:
Warning: mysqli_query() expects at least 2 parameters, 1 given in (...)
But if I instead use
$con = mysqli_connect("infos in here");,
$mysqli_query($con,"INSERT INTO and other info here");
The error goes away, and my script works.
My problem is that I need to use mysqli_query two different times in my page, and I don't want to open the connection again when it's already open.
How can I handle this?
Thanks.
My problem is that I need to use mysqli_query two different times in
my page, and I don't want to open the connection again when it's
already open.
How is it a problem ? open once query as many times then close the connection, example:
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform queries
mysqli_query($con,"SELECT * FROM Persons");
//one more
mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age)
VALUES ('Glenn','Quagmire',33)");
mysqli_close($con);
?>
No need to connect two times. An example here..
$con = mysqli_connect("host", "user", "password", "db");
if(mysqli_connect_errno()){
die(mysqli_connect_error());
}
//Query one
$result1 = mysqli_query($con, 'Query String');
//Query Two
$result2 = mysqli_query($con, 'Query String'); //Used same $con variable
//After finishing all queries
mysqli_close($con);
If you need to select multiple database then
$con = mysqli_connect("host", "user", "password");
//for DB bd_name1
mysqli_select_db($con, 'bd_name1');
$result1 = mysqli_query($con, 'Query String');
//for DB bd_name2
mysqli_select_db($con, 'bd_name2');
$result2 = mysqli_query($con, 'Query String');
But not connect frequent time.

How to insert data into mysql database using oops php5 concepts?

I am new for PHP5 OOP concept.
Please give some example source code for "How to insert data using oops concept?".I want to use pure php5 concept for this even in the connection.php page also.
I want to improve my knowledge. please any one help me....
I know below the basic concept
insert_db.php
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
connectio.php
<?php
// connect database code
$dbhost ='localhost';
$dbuser = 'tomking';
$dbpass = 'dsfds';
$dbname = 'mydb';
//connectivity of database
$conn = mysql_connect($dbhost,$dbuser,$dbpass) or die ('Error Connecting to mysql');
mysql_select_db($dbname);
?>
Use Mysqli or PDO for using sql queries instead of directly pass variables to query.
This will cause sql injection when you directly pass variable to query
If you want to pass variable to sql query , you have to use filters for this
filtering-escaping-post-data-from-injection-attacks
PDO Documentation
MySQLi Documentation
And this is all pure PHP5 concept.
$mysqli = new mysqli($hostname, $username, $password, $database_name);
if($mysqli->error)
die($mysqli->error);
$mysqli->query("SET NAMES 'UTF8'");
$query = "INSERT INTO my_table VALUES ('value_1', 'value_2')";
$mysqli->query($query);
if(!$mysql->error)
echo 'do something';
$query = "SELECT * FROM my_table";
$sql = $mysqli->query($query);
if($sql->num_rows > 0) {
while($row = $sql->fetch_assoc()) {
echo $row['field_1'];
}
}
$sql->close();

How do you connect to multiple MySQL databases on a single webpage?

I have information spread out across a few databases and want to put all the information onto one webpage using PHP. I was wondering how I can connect to multiple databases on a single PHP webpage.
I know how to connect to a single database using:
$dbh = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
However, can I just use multiple "mysql_connect" commands to open the other databases, and how would PHP know what database I want the information pulled from if I do have multiple databases connected.
Warning : mysql_xx functions are deprecated since php 5.5 and removed since php 7.0 (see http://php.net/manual/intro.mysql.php), use mysqli_xx functions or see the answer below from #Troelskn
You can make multiple calls to mysql_connect(), but if the parameters are the same you need to pass true for the '$new_link' (fourth) parameter, otherwise the same connection is reused. For example:
$dbh1 = mysql_connect($hostname, $username, $password);
$dbh2 = mysql_connect($hostname, $username, $password, true);
mysql_select_db('database1', $dbh1);
mysql_select_db('database2', $dbh2);
Then to query database 1 pass the first link identifier:
mysql_query('select * from tablename', $dbh1);
and for database 2 pass the second:
mysql_query('select * from tablename', $dbh2);
If you do not pass a link identifier then the last connection created is used (in this case the one represented by $dbh2) e.g.:
mysql_query('select * from tablename');
Other options
If the MySQL user has access to both databases and they are on the same host (i.e. both DBs are accessible from the same connection) you could:
Keep one connection open and call mysql_select_db() to swap between as necessary. I am not sure this is a clean solution and you could end up querying the wrong database.
Specify the database name when you reference tables within your queries (e.g. SELECT * FROM database2.tablename). This is likely to be a pain to implement.
Also please read troelskn's answer because that is a better approach if you are able to use PDO rather than the older extensions.
If you use PHP5 (And you should, given that PHP4 has been deprecated), you should use PDO, since this is slowly becoming the new standard. One (very) important benefit of PDO, is that it supports bound parameters, which makes for much more secure code.
You would connect through PDO, like this:
try {
$db = new PDO('mysql:dbname=databasename;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
echo 'Connection failed: ' . $ex->getMessage();
}
(Of course replace databasename, username and password above)
You can then query the database like this:
$result = $db->query("select * from tablename");
foreach ($result as $row) {
echo $row['foo'] . "\n";
}
Or, if you have variables:
$stmt = $db->prepare("select * from tablename where id = :id");
$stmt->execute(array(':id' => 42));
$row = $stmt->fetch();
If you need multiple connections open at once, you can simply create multiple instances of PDO:
try {
$db1 = new PDO('mysql:dbname=databas1;host=127.0.0.1', 'username', 'password');
$db2 = new PDO('mysql:dbname=databas2;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
echo 'Connection failed: ' . $ex->getMessage();
}
I just made my life simple:
CREATE VIEW another_table AS SELECT * FROM another_database.another_table;
hope it is helpful... cheers...
Instead of mysql_connect use mysqli_connect.
mysqli is provide a functionality for connect multiple database at a time.
$Db1 = new mysqli($hostname,$username,$password,$db_name1);
// this is connection 1 for DB 1
$Db2 = new mysqli($hostname,$username,$password,$db_name2);
// this is connection 2 for DB 2
Try below code:
$conn = mysql_connect("hostname","username","password");
mysql_select_db("db1",$conn);
mysql_select_db("db2",$conn);
$query1 = "SELECT * FROM db1.table";
$query2 = "SELECT * FROM db2.table";
You can fetch data of above query from both database as below
$rs = mysql_query($query1);
while($row = mysql_fetch_assoc($rs)) {
$data1[] = $row;
}
$rs = mysql_query($query2);
while($row = mysql_fetch_assoc($rs)) {
$data2[] = $row;
}
print_r($data1);
print_r($data2);
$dbh1 = mysql_connect($hostname, $username, $password);
$dbh2 = mysql_connect($hostname, $username, $password, true);
mysql_select_db('database1', $dbh1);
mysql_select_db('database2',$dbh2);
mysql_query('select * from tablename', $dbh1);
mysql_query('select * from tablename', $dbh2);
This is the most obvious solution that I use but just remember, if the username / password for both the database is exactly same in the same host, this solution will always be using the first connection. So don't be confused that this is not working in such case. What you need to do is, create 2 different users for the 2 databases and it will work.
Unless you really need to have more than one instance of a PDO object in play, consider the following:
$con = new PDO('mysql:host=localhost', $username, $password,
array(PDO::ATTR_PERSISTENT => true));
Notice the absence of dbname= in the construction arguments.
When you connect to MySQL via a terminal or other tool, the database name is not needed off the bat. You can switch between databases by using the USE dbname statement via the PDO::exec() method.
$con->exec("USE someDatabase");
$con->exec("USE anotherDatabase");
Of course you may want to wrap this in a catch try statement.
You might be able to use MySQLi syntax, which would allow you to handle it better.
Define the database connections, then whenever you want to query one of the database, specify the right connection.
E.g.:
$Db1 = new mysqli('$DB_HOST','USERNAME','PASSWORD'); // 1st database connection
$Db2 = new mysqli('$DB_HOST','USERNAME','PASSWORD'); // 2nd database connection
Then to query them on the same page, use something like:
$query = $Db1->query("select * from tablename")
$query2 = $Db2->query("select * from tablename")
die("$Db1->error");
Changing to MySQLi in this way will help you.
You don't actually need select_db. You can send a query to two databases at the same time. First, give a grant to DB1 to select from DB2 by GRANT select ON DB2.* TO DB1#localhost;. Then, FLUSH PRIVILEGES;. Finally, you are able to do 'multiple-database query' like SELECT DB1.TABLE1.id, DB2.TABLE1.username FROM DB1,DB2 etc. (Don't forget that you need 'root' access to use grant command)
if you are using mysqli and have two db_connection file. like
first one is
define('HOST','localhost');
define('USER','user');
define('PASS','passs');
define('**DB1**','database_name1');
$connMitra = new mysqli(HOST, USER, PASS, **DB1**);
second one is
define('HOST','localhost');
define('USER','user');
define('PASS','passs');
define(**'DB2**','database_name1');
$connMitra = new mysqli(HOST, USER, PASS, **DB2**);
SO just change the name of parameter pass in mysqli like DB1 and DB2.
if you pass same parameter in mysqli suppose DB1 in both file then second database will no connect any more. So remember when you use two or more connection pass different parameter name in mysqli function
<?php
// Sapan Mohanty
// Skype:sapan.mohannty
//***********************************
$oldData = mysql_connect('localhost', 'DBUSER', 'DBPASS');
echo mysql_error();
$NewData = mysql_connect('localhost', 'DBUSER', 'DBPASS');
echo mysql_error();
mysql_select_db('OLDDBNAME', $oldData );
mysql_select_db('NEWDBNAME', $NewData );
$getAllTablesName = "SELECT table_name FROM information_schema.tables WHERE table_type = 'base table'";
$getAllTablesNameExe = mysql_query($getAllTablesName);
//echo mysql_error();
while ($dataTableName = mysql_fetch_object($getAllTablesNameExe)) {
$oldDataCount = mysql_query('select count(*) as noOfRecord from ' . $dataTableName->table_name, $oldData);
$oldDataCountResult = mysql_fetch_object($oldDataCount);
$newDataCount = mysql_query('select count(*) as noOfRecord from ' . $dataTableName->table_name, $NewData);
$newDataCountResult = mysql_fetch_object($newDataCount);
if ( $oldDataCountResult->noOfRecord != $newDataCountResult->noOfRecord ) {
echo "<br/><b>" . $dataTableName->table_name . "</b>";
echo " | Old: " . $oldDataCountResult->noOfRecord;
echo " | New: " . $newDataCountResult->noOfRecord;
if ($oldDataCountResult->noOfRecord < $newDataCountResult->noOfRecord) {
echo " | <font color='green'>*</font>";
} else {
echo " | <font color='red'>*</font>";
}
echo "<br/>----------------------------------------";
}
}
?>

Categories