What am I missing with php command to INSERT INTO SELECT FROM? - php

I have a database and it contains four tables (for the sake of security I gave them disney character names) named huey, dewey, lewey and uncledonald.
I would like to have the data from the columns deweysays in the table dewey, hueysays from the table huey and leweysays from the table lewey to show up in thier corresponding columns in the table uncledonald. See attached pic to see visually what I mean.
4 tables
I've tried the following code and get the result I want but only once. After that I get data in the dewey, huey and lewey tables but nothing else in the uncledonald table.
<?php
//Let's see whether the form is submitted
if (isset ($_POST['submit'])) {
$con=mysqli_connect("localhost","root","root","provingground");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO dewey (lot_id, deweysays) VALUES (0, '{$_POST['deweyspeak']}');";
$sql .= "INSERT INTO huey (cust_id, hueysays) VALUES (0, '{$_POST['hueyspeak']}');";
$sql .= "INSERT INTO lewey (personal_id, leweysays) VALUES (0, '{$_POST['leweyspeak']}');";
$sql .= "INSERT INTO uncledonald (deweysays) SELECT deweysays FROM dewey ";
$sql .= "INSERT INTO uncledonald (hueysays) SELECT hueysays FROM huey ";
$sql .= "INSERT INTO uncledonald (leweysays) SELECT leweysays FROM lewey ";
// Execute multi query
if (mysqli_multi_query($con,$sql)){
print '<p> The Ducks Have Spoken.</p>';
} else {
die ('<p>Could not add entry because:<b>' . mysqli_error() . '</b>.</p><p>The query being run was: ' . $sql . '</p>');
}
}
mysqli_close($con);
?>
Is there something missing in my $sql query to uncledonald? Please help!

Related

How to insert data using one select in other database table

I have two databases and i have one table "TabelaX" in database "Servidor1" with out data and other database "Servidor2" with one table "TabelaY". And i want do one select in table "TabelaY" and with her data do one insert in table "TabelaX" which is in another database. I already made some code but it is not working correctly. And this error appears:
"Error: INSERT INTO TabelaX (ID, Nome, Dados) VALUES (2000, XPTO2,
12345); Unknown column 'XPTO2' in 'field list'Error: INSERT INTO
TabelaX (ID, Nome, Dados) VALUES (2033, XPTO3, 1234567890); Unknown
column 'XPTO3' in 'field list'"
<?php
$conn= mysqli_connect('localhost','root',null,'Servidor2') or die
(mysqli_connect_error());
if (!$conn) {
die("Falha de conexao: ". mysqli_connect_error());
}
$ID = $_POST['ID'];
$sql = "SELECT * FROM TabelaY WHERE ID = $ID";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$row1 = $row["ID"];
$row2 = $row["Nome"];
$row3 = $row["Dados"];
mysqli_select_db($conn,"Servidor1");
$sql = "INSERT INTO TabelaX (ID, Nome, Dados)
VALUES ($row1, $row2, $row3);";
if (mysqli_multi_query($conn, $sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
From what I have read, your current approach might be the only way to do this using regular queries with MySQL. But, if you were doing this directly on MySQL, you could just use a simple INSERT INTO ... SELECT:
INSERT INTO db1.TabelaX (ID, Nome, Dados)
SELECT ID, Nome, Dados
FROM db2.TabelaY;
One possibility would be to create a stored procedure on MySQL which does the above insert, and then call it from your PHP code:
$result = mysqli_query($conn,
"CALL YourProcName") or die("Query fail: " . mysqli_error());

Cannot send multiple mysql queries to my database via php

I've no idea what is going on here, but I cannot get two mysql statements to add content to my db via the mysql_query. Here is my code:
function sendDataToDB() {
// first send the user to the users table
$audio_survey = new dbclass();
$audio_survey -> connectToDB();
$sql = $_SESSION['user']['sql'];
$audio_survey -> queryTable($sql);
// get the current users' ID number from the table
$sql = "SELECT user_id FROM users WHERE name=\"" . $_SESSION['user']['name'] . "\"";
$result = $audio_survey -> queryTable($sql);
$output = $audio_survey -> getDataFromDB($result);
$user_id = $output['user_id'];
$songs = $_SESSION['songs'];
foreach ($songs as $song) {
$sql .= "INSERT INTO survey (user_id, song, genre, emotion, time_date) VALUES ($user_id, \"" . $song['song'] . "\", \"" . $song['genre'] . "\", \"" . $song['emotion'] . "\", \"" . $song['time_date'] . "\");<br />";
}
$audio_survey -> queryTable($sql);
$audio_survey -> closeDBconnection();
}
Everything works, as in a user gets added to my "users" table, but when the variable $sql is passed into mysql_query then I get this error:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO survey (user_id, song, genre, emotion, time_date) VALUES (3, "one mo' at line 1
I've tried pasting in the statement I have concatenated using the $sqlvariable straight into the sql query box in phpMyAdmin and it works! This is what the foreach loop produces that works in phpMyAdmin, but not the mysql_query function! I've made sure I have allocated enough space for characters, etc.
INSERT INTO survey (user_id, song, genre, emotion, time_date) VALUES (3, "one more time", "dance", "happy", "15:32:21 07-11-14");
INSERT INTO survey (user_id, song, genre, emotion, time_date) VALUES (3, "dance dance dance", "disco", "relaxed", "15:32:28 07-11-14");
http://php.net/manual/en/function.mysql-query.php
mysql_query() sends a unique query (multiple queries are NOT supported)
Docu-cite-service (tm)
You need to either use Nisse's approach, while calling mysql_query() inside the loop - or use something else, that allows to execute multiple queries within one statement rather than the deprecated mysql_query method.
Another option would be to rewrite your concatenation logic, so it generates one query for multiple inserts:
INSERT INTO survey
(user_id, song, genre, emotion, time_date)
VALUES
(3, "one more time", "dance", "happy", "15:32:21 07-11-14"),
(3, "dance dance dance", "disco", "relaxed", "15:32:28 07-11-14"),
...
something like
$sql = "INSERT INTO survey (user_id, song, genre, emotion, time_date) VALUES ";
$atLeastoneInsert = false;
foreach ($songs as $song) {
$atLeastoneInsert = true;
$sql .= "($user_id, \"" . $song['song'] . "\", \"" . $song['genre'] . "\", \"" . $song['emotion'] . "\", \"" . $song['time_date'] . "\"),";
}
$sql = trim($sql,",");
if ($atLeastoneInsert){
$audio_survey -> queryTable($sql);
}
$sql = "SELECT user_id FROM users ...";
...
foreach ($songs as $song) {
$sql .= "INSERT INTO survey ...";
}
You are adding all the queries together using the (.=) string concatenation operator. You need to use normal assignment, and move queryTable($sql) into the loop.
foreach ($songs as $song) {
$sql = "INSERT INTO survey ...";
$audio_survey -> queryTable($sql);
}
Note also that the MySQL extension is deprecated and will be removed in the future. You should use MySQLi or PDO instead.

Modify insert into to update

I want to modify my code so instead of just inserting a new row in the MySQL table, it can check to see if there is one with the same item number, and update it.
php code
<?php
$con=mysqli_connect("localhost","root","root","inventory");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO `current stock` (ItemNumber, Stock)
VALUES
('".$_POST['ItemNumber']."', '".$_POST['Stock']."' )";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
You can use ON DUPLICATE KEY UPDATE syntax,
$sql = "
INSERT INTO `current stock` (ItemNumber, Stock)
VALUES ('$_POST[ItemNumber]', '$_POST[Stock]' )
ON DUPLICATE KEY UPDATE
Stock = '$_POST[Stock]'
";
ItemNumber should be primary/unique key in this case

Insert output data to database of an web page

i have a output page of the following php code..
include('../simple_html_dom.php');
// get DOM from URL or file
$html = file_get_html('http://www.wine-searcher.com/merchant/852');
$data=$html->find('td.firstcell');
echo "Country :". $data[0].'<br />';
echo "Email :".$data[2].'<br />';
echo "Postal Address :".$data[3].'<br />';
echo "Permanent Address :".$data[4].'<br />';
echo "Contact :".$data[10].'<br />';
the output value of the script is to be inserted in to the database like MySQL.
for that i try something like that..
<?php
// example of how to use basic selector to retrieve HTML contents
include('../simple_html_dom.php');
// get DOM from URL or file
$html = file_get_html('http://www.wine-searcher.com/merchant/852');
$data=$html->find('td.firstcell');
$con = mysql_connect("localhost","user","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Create database
if (mysql_query("CREATE DATABASE nt_usawine",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
// Create table
mysql_select_db("nt_usawine", $con);
$sql = "CREATE TABLE Persons
(
FirstName varchar(15),
LastName varchar(15),
Age int
)";
// Execute query
mysql_query($sql,$con);
$foo= $data[2];
mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin', $foo)");
mysql_close($con);
echo "Country :". $data[0].'<br />';
echo "Email :".$data[2].'<br />';
echo "Postal Address :".$data[3].'<br />';
echo "Permanent Address :".$data[4].'<br />';
echo "Contact :".$data[10].'<br />';
but still i cant get the table in the database with my data inserted. what is the right way to save the data ?
Have you tried to debug this by using mysql_error ?
$query = "INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin', $foo)";
$result = mysql_query($query);
if (!$result) {
$message = 'There is an error : ' . mysql_error() . "\n";
$message .= 'The query was : ' . $query;
die($message);
}
If you have an SQL error this would be very usefull.
By the way have you seen the only once time you don't do mysql_query( [...], $con) it the once which should add datas ?
And is it normal that you create a database and a table each time ? (don't know what you really want to do)
The mysql_query(); function allows you to run a query. Using the INSERT syntax you can insert data.
Example:
mysql_query("INSERT INTO `table` (`column1`, `column2`) VALUES ('value1', 'value2')");
Currently, what I'm seeing you wish to insert the country, email, postal address, permanent address and contact even though you create a table that can hold the data firstname, lastname and age...
No offence, but if you're already stuck there, this is not the right place to post your question. You need to search some tutorials before you even consider asking. SQL queries are well documented and can be found all over the web.
Either way, I'm too kind to leave this question unanswered.
I advice to create your database and table in PhpMyAdmin, rather creating a new one in your script. It's rather inefficient.
<?php
// this is where you login to your database
$connection = mysql_connect('localhost', 'username', 'password') or die('Could not connect: ' . mysql_error());
// select your EXISTING database you created. Usually there's a single database linked to your website
mysql_select_db('database_name', $connection);
// inserting data into table
$success = mysql_query("INSERT INTO `table_name` (`country`, `email`, `postaladdr`, `permanentaddr`, `contact`) VALUES ('".mysql_real_escape_string($data[0])."', '".mysql_real_escape_string($data[2])."', '".mysql_real_escape_string($data[3])."', '".mysql_real_escape_string($data[4])."', '".mysql_real_escape_string($data[10])."')");
// check if insert was successful
if($success) {
echo 'data inserted';
} else {
echo 'Something went wrong: ' . mysql_error();
}
// closing database
mysql_close($connection);
?>
Now all you have to do is change the login data, change the database_name, create the actual table and change the table_name in the script.
This is one of the first things you learn when starting with running SQL queries, so I higly suggest to learn more: http://www.w3schools.com/php/php_mysql_intro.asp
If everything I said didn't make any sense, you should click the link above.

Check if value exists before inserting into MySQL DB in a PHP script

I've looked for similar questions with no success.
I have this piece of code:
form1.php
$query = "INSERT INTO table1 ";
$query .= "(fname, lname, mail)";
$query .= " VALUES ";
$query .= "('".$_POST[fname]."', '".$_POST[lname]."', '".$_POST[mail]."')";
$result = mysql_query($query) or die ("Query Failed: " . mysql_error());
And I want that the script will check if the value inserted exists in the corresponding column, and throw an error if it does. any ideas?
Create a UNIQUE key on the fields you care about, and detect the integrity error after the fact.

Categories