See the code below, there are two databases connections.
First it get the data from first connection and then insert into second database connection but it will not insert - I can an error saying Unknown column 'fullname' in 'field list'
When I tried SQL query manually in phpMyAdmin and it work fine...
$db_new = mysql_connect('localhost', 'root', 'password');
if (!mysql_select_db("menu_new", $db_new)) {
die("Cant connect menu_new DATABASE");
}
$db_old = mysql_connect('localhost', 'root', 'password');
if (!mysql_select_db("old_menu", $db_old)) {
die("Cant connect old_menu DATABASE");
}
$SQL_old = "SELECT * FROM old_table";
$q = mysql_query($SQL_old, $db_old);
while ($row = mysql_fetch_assoc($q)) {
$name = $row['name'];
$SQL = "INSERT INTO tbl_name (fullname) values ('$name')";
//Problem Here - It wont insert into second database
mysql_query($SQL, $db_new) or die(mysql_error($db_new));
}
Nothing is strange in this behavior. Just add the $link parameter on your mysql_connect calls, and set it to true. By default it is False and it means that reusing this function with the same parameters, which is what you're doing as the db name is not on your mysql-connect, will reuse existing connexion with same parameters. So you have two variables but only one connexion.
It means you're simply moving the db used in this connexion. Prefixing with the db name fixed the problem as MySQL allow inter-base manipulations from the same connexion if it's on the same db server.
Thanks #Konerak for suggestion and that does work!
To Insert/Select data from Database connection, you will have to include database name before the table name.
For Example
From:
mysql_query("INSERT into tbl_name (fullname) values ('1')", $db_new) or die(mysql_error($db_new));
To:
mysql_query("INSERT into menu_new.tbl_name (fullname) values ('1')", $db_new) or die(mysql_error($db_new));
That is really odd though.
Related
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.
Using the given below php script, I connect to database and insert data in it. But the data is not getting inserted in my database table. It is also not throwing any error. Where is my code wrong?
<?php
$host = '127.0.0.1';
$uname='root';
$pswd='';
$myDB='portal';
if($myConn = new mysqli($host,$uname,$pswd))
echo 'Connected to MySQL server successfully.</br>';
else
echo 'Unable to connect to server</br>';
$database = mysqli_select_db($myConn,$myDB);
if($database)
echo 'Connected to database...</br>';
else
echo 'Database not found!</br>';
$var1='string1';
$var2='string2';
$query= "INSERT INTO users VALUES ($var1,$var2)";
$result = mysqli_query($myConn,$query) or die(mysqli_error($myConn));
?>
You have to add single quotes around the values:
$query= "INSERT INTO users VALUES ('$var1','$var2')
Or better use prepared statements. See this for an example.
In your statement, you must define the names of the target tables in your database, that the values should be inserted into, like this:
$query= "INSERT INTO users (Name,Age) VALUES ('$name','$age')";
if users table have only two columns, or two plus an auto-incrementing id the query is:
INSERT INTO users VALUES ('$var1','$var2')
if there are more columns or a non primary id the query is:
INSERT INTO users (col1,col2) VALUES ('$var1','$var2')
You also miss a parameter in the connection instantiation:
$mysqli = new mysqli($host, $uname,$pswd, $myDB);
I want to insert new rows from local table to remote table, i have made a php script for it but it is not working.
Remote and local - database, table and fields are same.
I am doing this way
//connection
$remote_hostname='xxx.xxx.xxx.xxx:3306';
$hostname='localhost';
$username = 'username';
$password = 'password';
$remote_connection = mysql_connect($remote_hostname, $username, $password);
$connection = mysql_connect($hostname, $username, $password);
$tablename="pc_games";
$database = 'games';
// some row count here $remoterows
$local_query = "SELECT * FROM $tablename LIMIT 100 OFFSET $remoterows";
$local_result = mysql_query($local_query, $connection) or trigger_error(mysql_error());
while($list=mysql_fetch_array($local_result))
{
$remote_update=mysql_query("INSERT INTO $tablename SELECT * from $tablename");
$remote_update_result = mysql_query($remote_update, $remote_connection) or trigger_error(mysql_error());
}
This is not working and showing error Duplicate entry '1' for key 'PRIMARY', but there is no duplicate entry.
If i do it this way it works, new rows get inserted into remote database.
while($list=mysql_fetch_array($local_result))
{
$id=$list['id'];
$pflink=$list['pflink'];
$image=$list['image'];
$pagelink=$list['pagelink'];
$title=$list['title'];
// and so on...
$remote_update=mysql_query("INSERT INTO $tablename SET id='$id', image='$image', pagelink='$pagelink', title='$title'......");
$remote_update_result = mysql_query($remote_update, $remote_connection) or trigger_error(mysql_error());
}
I have a many colums in database and also many database, i want to do it the first way, as i want to re use these codes for another database with just changing $database and $tablename
in require file for another database.
Please see and suggest any possible way to do it.
You cannot span a local and remote query in one request:
$remote_update=mysql_query("INSERT INTO $tablename SELECT * from $tablename");
This is supposed to get data from the local select and insert it into the remote database?
The query operates on 1 database, and 1 database only. You are trying to fetch data from a table and insert it on the same table. And of course, this gives a Duplicate entry '1' for key 'PRIMARY'
despite the question is so old, you can check "CLONE" supported from MYSQL 8.0.17: https://dev.mysql.com/doc/refman/8.0/en/clone-plugin-remote.html
This allow copy from localDB to remoteDB so easy.
Thanks for taking a look:
Here is the php I'm using to insert the data into the table
<?php
session_start();
//sets a variable from a session value
if (isset($_SESSION['sv_01'])) {$sv_01=$_SESSION['sv_01'];} else {$sv_01="";}
//to test that the variable has been set and is not empty
echo $sv_01;
//define database log in stuff
$username="username123";
$password="password123";
$database="database01";
$table="my_table";
$dbaddress="123.123.123.123";
//connect to dbserver
$con=mysql_connect($dbaddress,$username,$password);
if (!$con)
{
die('Could not connect:' .mysql_error());
}
//select the db
mysql_select_db($database) or die( "Unable to select database");
//insert data from variables
mysql_query("INSERT INTO $table
(
$sv_01
)
VALUES
(
'$sv_01'
)");
mysql_close($con);
?>
I run this, and then go to check out the contents of the DB. Using MySQL workbench I open the connection and the database and table in question, select all rows and there is no data contained in the table.
MySQL info:
Collation: latin1 - default
collation Engine: MyISAM
datatype: sv_01 VARCHAR (255)
default: NULL
Any ideas what I am doing incorrectly?
I believe that the name of the field is sv_01 not $sv_01
I would try:
$query = "INSERT INTO $table (sv_01) VALUES ('$sv_01')";
Update (dedicated to tadman):
A small piece of advice: DO NOT use mysql_query
Use localhost insted af your IP (if possible), and make your connection easy to read:
$con=mysql_connect($dbaddress,$username,$password) OR DIE mysql_error();
AND you also have to give you mysql_query a variable:
$mysql = mysql_query("INSERT INTO $table ($sv_01) VALUES ('".$sv_01."');");
:)
I can get it to work from home which I coded using mysqli but my school doesn't have that enabled so now it wont execute the query what am I doing wrong or is there a better way of doing this?
!!!Update!!!
So I connected to my website at home the one that works and redid the connection by just removing the i form the connections and the extra field (database name) in $dbc and it started getting errors. this happened even before I removed the database name from the connection. So I realized that the script doesn't know what database I'm connecting to. How can I fix this?
Home (works)
/* database connection */
$dbc = mysqli_connect('localhost', 'user', '9890667', 'zombies')
or die('Error Connecting to the MySQL Server');
/* insert query */
$query = "INSERT INTO zombie_sighted (first_name,last_name, when_it_happened, how_long, how_many, zombie_description, what_they_were_doing, fang_spotted, other, email) " .
"VALUES ('$first_name','$last_name','$when_it_happened','$how_long','$how_many','$zombie_description','$what_they_did','$fang_spotted','$other','$email')";
/* execute query */
$result = mysqli_query($dbc, $query)
or die('Error querying database.');
mysqli_close($dbc);
School(connects but query doesn't work now) Updated
$dbc = mysql_connect('shcool url', 'username, 'password')
or die('Error Connecting to the MySQL Server');
/* insert query */
$query = "INSERT INTO zombie_sighted (first_name,last_name, when_it_happened, how_long, how_many, zombie_description, what_they_were_doing, fang_spotted, other, email) " .
"VALUES ('$first_name','$last_name','$when_it_happened','$how_long','$how_many','$zombie_description','$what_they_did','$fang_spotted','$other','$email')";
/* execute query */
$result = mysql_query($dbc, $query)
or die('Error querying database.');
mysql_close($dbc);
Are you certain localhost is the correct MySQL path at your school location? If this is a shared server that doesn't allow things like shell access I bet the db path is not localhost as it would be on a dedicated box.
$result = mysql_query($query) try this.
mysql_query
you pass the resource in as first param when the query string is supposed to be. also, make sure your mysql_connection fields are correct.