MYSQL, PHP two connections inside while loop - php

I have two databases on the same MYSQL server.
I want to be able to query one table on one database, and use the results for an insert into the other table (on the other data base). I've tried moving the mysql_select_db lines around to no avail. Please note this is a one off internal script so security is not a concern (Don't want to us mysqli)
<?php
// Connecting, selecting database
$link1 = mysql_connect('127.0.0.1', 'username', 'password', true)
or die('Could not connect: ' . mysql_error());
$link2 = mysql_connect('127.0.0.1', 'username', 'password', true)
or die('Could not connect: ' . mysql_error());
mysql_select_db('db1', $link1) or die('Could not select database');
mysql_select_db('db2', $link2) or die('Could not select database');
// Performing SQL query
$query = "select fields from table";
$result = mysql_query($query,$link1) or die('Query failed: ' . mysql_error());
while ($row = mysql_fetch_array($result)){
$querynew = "insert into table (blah,blah) values ('$row['name']',$row['name2']')";
mysql_query($querynew, $link2);
}

You can use plain SQL for this to minimize traffic across the wire:
INSERT INTO `db2.tbl1` (`field1`,`field2`)
SELECT `field1`, `field2` FROM `db1.tbl2` WHERE `someCondition`='IsMet'

Related

Trouble inserting data into mysql table with php

I have a few string variables I am trying to insert them into my DB but I am having trouble because nothing is being inserted into the DB. I know the variables are populated. Since all variables are string I'm converting some of them to integers because those fields in the db table are type integer. I tried assigning the mysql_query to a variable and then check to return an error but it didn't display anything. I'm a bit new at PHP so I'm not sure what's wrong with my code below. I appreciate the help.
$connect = mysql_connect("localhost", "user", "pass");
if (!$connect) { die("Could not connect: ". mysql_error()); }
mysql_select_db("dbname");
mysql_query($connect,"INSERT INTO table1 (id, AU, TI, JO, VL, ISS, PB, SN, UR, DO, SP, EP, PY) VALUES ('NULL', '".$authors."', '".$title."', '".$journal."', '".(int)$volume."', '".(int)$issue."', '".$publisher."', '".$serial."', '".$url."', '".$doi."', '".(int)$startpage."', '".(int)$endpage."', '".(int)$year."')");
mysql_close($connect);
Try to debug your code, adding some more useful checks.
$link = mysql_connect("localhost", "user", "pass");
if (!$link) {
die("Could not connect: ". mysql_error());
}
$dbSelected = mysql_select_db("dbname", $link);
if (!$dbSelected) {
die ("Can't select db: " . mysql_error());
}
$result = mysql_query("YOUR_QUERY", $link);
if (!$result) {
die("Invalid query: " . mysql_error());
}
ps: you may want to use mysqly::query, just because mysql_query is deprecated
ps2: you should google about SQL Injection, since your statement doesn't look secure (unless those values are escaped somewhere)
NOTE: I just noticed that you are using a wrong order for the parameters on mysql_query($query, $link). You have put $link as first parameter.

Can 1 PHP file connects to 2 databases?

I am trying to connect to the first database to pull some information, then update a table in the second database with that information.
However, the second query always tries to pull from the first database if I don't close the connection. If I do close the connection, then it gives me a socket error.
I am using Drupal (so my first database is the Drupal database). I want to get a value from one of those tables and put it in my Member Info database whenever 1 of 3 different PHP pages load.
Is this possible?
Yes, you can create multiple connections. You need to specify the link inside mysql_query as second arguements.
Example :
$link1 = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link1) {
die('Not connected : ' . mysql_error());
}
// second foo1
$db_selected_1 = mysql_select_db('foo1', $link1);
if (!$db_selected_1) {
die ('Can\'t use foo : ' . mysql_error());
}
$link2 = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link2) {
die('Not connected : ' . mysql_error());
}
// select foo2
$db_selected_2 = mysql_select_db('foo2', $link2);
if (!$db_selected_2) {
die ('Can\'t use foo : ' . mysql_error());
}
// query on first db
mysql_query('SELECT * FROM 1 WHERE 1', $link1);
// query on second db
mysql_query('SELECT * FROM 1 WHERE 1', $link2);
If you have the same crendetials on the same server for both database, you could just do this :
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// select foo1
$db_selected = mysql_select_db('foo1', $link);
// query on first db
mysql_query('SELECT * FROM 1 WHERE 1', $link);
// select foo2
$db_selected = mysql_select_db('foo2', $link);
// query on second db
mysql_query('SELECT * FROM 1 WHERE 1', $link);
I however suggest you to use mysqli_ or even PDO.
You can store multiple connections concurrently.
There is no limit in PHP that will stop you from doing that.
If you're having a problem with specific code, please update the question.

php insert mysql not working

.I don't know if it's syntax or what. I've tried a variety of ways this is the simplest I thought would work.
I send info to the userData.php using:
http://mydomain.com/adverts/userStats.php?name=001EC946C2F4&adNum=1&playClick=1
On the userData.php I have:
<?php
$db = mysql_connect('localhost', 'username', 'password') or die('Could not connect: ' . mysql_error());
$db_selected = mysql_select_db('databaseName', $db) or die('Could not select database');
if (!$db_selected)
{
die ("Can\'t use test_db : " . mysql_error());
}
$name = mysql_real_escape_string($_GET['name']);
$date = date("d/m/Y");
$adClick = mysql_real_escape_string($_GET['adNum]);
$playN = mysql_real_escape_string($_GET['playClick']);
$query = mysql_query("INSERT INTO playerData VALUES ('$name', '$date','$adClick','$playN')");
$result = mysql_query($query) or die('Query failed: ' . mysql_error()));
mysql_close($db);
?>
I manually added 2 records to the table from phpMyAdmin, and I can display or update them just fine but adding a new record isn't working. I simply want to start a new record each time the link is called from another program, and store the mac address, date, adNum, and playClick.
EDIT2:: echo $query; for
http://simplehotkey.com/adverts/userStats.php?name=001EC946C2F4&adNum=1&playClick=1
outputs:
INSERT INTO playerData(mac,date,AdClick,PlayNum) VALUES ('001EC946C2F4', '26/07/2012','1','1')
Which is what I want it's just not adding it to the DB.
Correct syntax is --
mysql_select_db("databaseName", $db);
And its better if u use something like this for connection errors--
$db_selected= mysql_select_db("databaseName", $db);
if (!$db_selected)
{
die ("Can\'t use test_db : " . mysql_error());
}
EDIT
You are writing all wrong :(
$query = mysql_query("INSERT INTO playerData VALUES ('$name', '$date','$adClick','$playN')");
$result = mysql_query($query) <--------------WRONG
Try Something like this----
$query = "INSERT INTO playerData(CORRECT_COL_NAMES) VALUES ('$name', '$date','$adClick','$playN')";
$results = mysql_query($query, $connection);
NEW EDIT
AREA OF ERROR---- WRONG DATATYPE
','1','1' <--- this is passing as string while u have have this as an int in your db structure ..now run the same query as it is to figure out the error..also u can figure out using $result = mysql_query($query) or die(mysql_error());
It's pretty easy to see what's wrong here, especially with syntax highlighting.
$adClick = mysql_real_escape_string($_GET['adNum]);
This line is missing a single quote mark; it should be:
$adClick = mysql_real_escape_string($_GET['adNum']);
This is a syntax error that ruins everything else.
Not to mention that your database selection is missing your database handler, ie:
mysql_select_db('databasename',$db);
As pointed out by #swapnesh, and as noted here.
Edit
I have been unable to reproduce your lack of an error, what I have gotten however, are errors. Firstly, you have an extra ) at line 12:
$result = mysql_query($query) or die('Query failed: ' . mysql_error()));
Should be:
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
Lastly, you actually improperly execute your query twice, so the second time, the query is empty. What you have:
$query = mysql_query("INSERT INTO playerData VALUES ('$name', '$date','$adClick','$playN')");
$result = mysql_query($query) or die('Query failed: ' . mysql_error()));
Should instead be:
$query = "INSERT INTO playerData VALUES ('$name', '$date','$adClick','$playN')";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
Instead of using the insert statement the way you do add the fields that will receive entries explicitly. The database table might have more fields and the insert statement does not explcitly state which fields will receive data.
$query = mysql_query("INSERT INTO playerData (Name,Date,AdClick,PlayN) VALUES ('$name', '$date','$adClick','$playN')");
You have the syntax error on this line
Wrong :
$adClick = mysql_real_escape_string($_GET['adNum]);
Correct :
$adClick = mysql_real_escape_string($_GET['adNum']);

mysql query not inserting string into table?

I have been able to manually insert values in my table using phpmyadmin, and even if i end up using the same php code i get from php my admin to call the query it STILL won't add the value to the table. here is the code:
<?php
$link = mysql_connect('localhost', 'username', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db('sc2broating1', $link);
$sql = "INSERT INTO `sc2broad_tesing1`.`Persons` (`re`) VALUES (\'hello11\')";
mysql_query($sql);
mysql_close($link);
?>
Don't escape value.
$sql = "INSERT INTO `sc2broad_tesing1`.`Persons` (`re`) VALUES ('hello11')";
I would also consider using bound parameters, as seen in mysqli::prepare, if Mysqli is an option.

insert to 2 tables from single form code is giving problem----please help

I have a webform, from which i want records should be submitted into two tables under same database name.
My code is
<?php
$con = mysql_connect("localhost","************","***********");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db=mysql_select_db("qserves1_uksurvey", $con);
$sql="INSERT INTO forms (date, Receivingsky, Title, Firstname, Lastname, House, Street, Town, County, Postcode, Number, WarrantyCoverForSky, Tvmake, Warrantycover, Payingmonthly, Agentnotes, Agentname)
VALUES
(NOW(),'$_POST[Receivingsky]','$_POST[Title]','$_POST[Firstname]','$_POST[Lastname]','$_POST[House]','$_POST[Street]','$_POST[Town]','$_POST[County]','$_POST[Postcode]','$_POST[Number]','$_POST[WarrantyCoverForSky]','$_POST[Tvmake]','$_POST[Warrantycover]','$_POST[Payingmonthly]','$_POST[Agentnotes]','$_POST[Agentname]')";
$sql_result = mysql_query($sql, $con) or die (mysql_error());
$con2 = mysql_connect("localhost","*******8","*********8");
if (!$con2)
{
die('Could not connect: ' . mysql_error());
}
$db2=mysql_select_db("qserves1_uksurvey", $con2);
$sql2="INSERT INTO dupphones (date, Number)
Values
(NOW(),'$_POST[Number]')";
$sql_result = mysql_query($sql2, $con2) or die (mysql_error());
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo '<html>
<head>
<title>Lead Submitted successfully!!!</title>
</head>
<body>
<center>
<strong>Lead Submitted ---- Click Here To Enter New Lead</strong>
</center>
</body>
</html>!';
mysql_close($con)
?>
This is submitting 3 leads 1 is in table dupphones and 2 leads in table forms.
I want this to submit 1 lead in each table only.
Please help
Thanks
You create two connections to the same database. You also execute mysql_query numerous times, sometimes with $sql2, then again with $sql. To clear up your code a little bit this is how it could look:
<?php
$con = mysql_connect("localhost","************","***********");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db=mysql_select_db("qserves1_uksurvey", $con);
$sql="INSERT INTO forms (date, Receivingsky, Title, Firstname, Lastname, House, Street, Town, County, Postcode, Number, WarrantyCoverForSky, Tvmake, Warrantycover, Payingmonthly, Agentnotes, Agentname)
VALUES
(NOW(),'$_POST[Receivingsky]','$_POST[Title]','$_POST[Firstname]',
'$_POST[Lastname]','$_POST[House]','$_POST[Street]','$_POST[Town]','$_POST[County]',
'$_POST[Postcode]','$_POST[Number]','$_POST[WarrantyCoverForSky]','$_POST[Tvmake]',
'$_POST[Warrantycover]','$_POST[Payingmonthly]','$_POST[Agentnotes]',
'$_POST[Agentname]')";
$sql_result = mysql_query($sql, $con) or die (mysql_error());
$sql2="INSERT INTO dupphones (date, Number)
Values
(NOW(),'$_POST[Number]')";
$sql_result = mysql_query($sql2, $con2) or die (mysql_error());
echo '<html>
<head>
Note that your queries are still vulnerable to sql injection. Use escaping or prepared statements to get rid of sql injection.
Just a few words of advice. Sanitize your $_POST data before you submit. And consider using a primary key. Also, why do you make a new connection to run the second query?
At least use mysql_real_escape()
You get two queries because you do
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
Which runs the query again. You already run it once on top
$sql_result = mysql_query($sql, $con) or die (mysql_error());

Categories