i have json as input
$page = file_get_contents('http://example.com/products.html');
$items = json_decode($page, true);
if i put echo $page; i get smth like this
{
"productlist":[
{
"id":"1",
"cat":"milk",
"prod_name":"happy milk",
"img_url":"http://example.com/milk.jpg"},
{
"id":"2",
"cat":"bread",
"prod_name":"black bread",
"img_url":"http://example.com/bread.jpg"},
then, i want to put it into MySQL DB
foreach($items['productlist'] as $item) {
$id = $item['id'];
$cat = $item['cat'];
mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, $cat)") or die(mysql_error());
}
at this stage i get nothing. if i modify code into
foreach($items['productlist'] as $item) {
$id = $item['id'];
mysqli_query($link, "INSERT INTO table (id) VALUES ($id)") or die(mysql_error());
}
i get the table in DB filled - i have two rows with prod id. Ok, i want to insert into table the $cat = food
foreach($items['productlist'] as $item) {
$id = $item['id'];
$cat = 'food';
mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, $cat)") or die(mysql_error());
}
yet this does not work, i get null result. but if i modify query into
foreach($items['productlist'] as $item) {
$id = $item['id'];
mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, 'food')") or die(mysql_error());
}
i get the result i seek for - tho rows in table, filled with id and cat
id cat
1 food
2 food
does anyone know how to send string value into insert query via variable?
That doesn't work because cat is a String field, need to be between quotes '...'. try this :
mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, '$cat')") or die(mysql_error());
or this :
mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, ".$cat.")") or die(mysql_error());
First, I would suggest you to learn how to use prepared statements, as you are getting your strings outside of your code (it may contain some mysql injections).
To answer your question, you need to put some quotes around the variable you want to put in your query as it is a string, so mysql can interpret it correctly
mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, '$cat')") or die(mysql_error());
Try this
mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, ".mysql_real_escape_string($cat).")") or die(mysql_error());
Related
I want to insert two values into the same table of SQL. The first value comes from another table and the other value is argv[2].
This is the code that I am using but it does not work.
for($i=0;$i<=feof($getdata);$i++){
if (filter_var($data[$i][1], FILTER_VALIDATE_EMAIL)){
//echo $data[$i][1];
$email=$data[$i][1];
$type=$argv[2];
$name=$data[$i][0];
$sql ="INSERT INTO promo_user (name,email) VALUES ('$name','$email')";
mysqli_query($conn,$sql);
$uid = mysqli_insert_id($conn);
$sql ="INSERT INTO promo_type set uid =$uid";
mysqli_query($conn,$sql);
$sql = "INSERT INTO promo_type (type) values ('$type')";
mysqli_query($conn,$sql);
}
}
mysqli_close($conn);
What is the proper way to reference the array components from fetch_assoc() so that they can be inserted into another table?
Here is my current code:
$sql_read = "SELECT id, data1, data2, date FROM `table1`";
$result = $mysqli->query($sql_read);
if ($result !== false) {
$rows = $result->fetch_all();
}
while ($row = $result->fetch_assoc()){
$sql_write = "INSERT INTO `table2`.`load_records` (`id`, `data1`,`data2`,`date`) VALUES ('.$row['id']', '.$row['data1']', '.$row['data2']', '.$row['date']', NULL);";
}
As suggested in my comment, first your select statement should be:
"SELECT id, data1, data2, date FROM `table1`";
Furthermore, the insert statement should be (see the use of concatenation of strings):
"INSERT INTO `table2`.`load_records` (`id`, `data1`,`data2`,`date`) VALUES ('".$row['id']."', '".$row['data1']."', '".$row['data2']."', '".$row['date']."', NULL);";
There are some errors in your script, as already pointed out.
But you might also be interested in the INSERT INTO ... SELECT variant of the INSERT syntax.
<?php
$query = '
INSERT INTO
table2
(`id`, `data1`,`data2`,`date`)
SELECT
`id`, `data1`,`data2`,`date`
FROM
table1
';
$result = $mysqli->query($query);
if ( !$result ) {
trigger_error('error: ' . $mysqli->error, E_USER_ERROR);
}
else {
echo $mysqli->affected_rows, ' rows have been transfered';
}
You have an extra field in the VALUES that is not referenced in the INTO and the concatenation of the row data is incorrect;
$sql_write = "INSERT INTO `table2`.`load_records`
(`id`, `data1`,`data2`,`date`)
VALUES ('.$row['id'].', '.$row['data1']', '.$row['data2']', '.$row['date']', NULL);";
should be:
$sql_write = "INSERT INTO `table2`.`load_records`
(`id`, `data1`,`data2`,`date`)
VALUES ('".$row['id']."', '".$row['data1']."', '".$row['data2']."', '".$row['date']."');";
Or you need to update the INTO to include an extra column that accepts NULL
See also:
The PHP reference on mysqli_result::fetch_assoc
I'm trying to grab SID from the insert into the first table (stories) so I can insert that SID into the writing table in my second insert.
I think the way to do this is with mysql_insert_id(); after the first query, but the primary key that auto-increments is called SID. If mysql_insert_id() could grab that value I'd be all set.
What I am finding from a var_dump is that the $SID = mysql_insert_id(); is just returning the value "0" and I'm not sure why.
There is a column called ID in stores, but if it was grabbing that, the value would be "1". Either way, I wish this method could be written as mysql_insert_SID();
Any idea what I am doing wrong or how I can fix this? And yes, I know this is a deprecated approach, but first I want to figure out how before I worry about converting to PDO.
// Get values from form
$category = $_POST['category'];
$genre = $_POST['genre'];
$story_name = $_POST['story_name'];
$text = $_POST['text'];
$query = "INSERT INTO stories (ID, category, genre, story_name, active) VALUES
('$user_ID', '$category', '$genre','$story_name', '1')";
$result = mysql_query($query);
$SID = mysql_insert_id();
$SID2 = "select stories.SID from stories where stories.SID=$SID";
$query2 = "INSERT INTO writing (ID, SID, text, position, approved)
VALUES('$user_ID', '$SID2', '$text', '1','N')";
$result = mysql_query($query2);
Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
(http://php.net/manual/en/function.mysql-insert-id.php)
But you aren't executing any query (via mysql_query()). You're just assigning your query to a variable. Try following:
$query = "INSERT INTO stories (ID, category, genre, story_name, active) VALUES
('$user_ID', '$category', '$genre','$story_name', '1')";
mysql_query($query);
$SID = mysql_insert_id();
I think you've forgotten to execute the query most probably?
Try
$SID = mysql_insert_id();
after executing the query
$query = "INSERT INTO stories (ID, category, genre, story_name, active) VALUES
('$user_ID', '$category', '$genre','$story_name', '1')";
$result = mysql_query($query); // executing
$SID = mysql_insert_id(); // order of queries is important
If you cannot get the value through mysql_insert_id() then try SELECT LAST_INSERT_ID(). Of course there will be a value if you have executed an insert query with AUTOINCREMENT (which you haven't done yet)
I try next script:
// Insert data into mysql
$qry="INSERT INTO $tbl_name1 (ID, REFERENCE, CODE, NAME) VALUES (UUID(), '$REFERENCE', '$CODE', '$NAME')";
$result=mysql_query($qry);
$qry2="INSERT INTO $tbl_name2 (PRODUCT) VALUES ('$ID')"; <--- Here is a problem
$result=mysql_query($qry2)
I do not know how two insert the same UUID in two tables simultanoiusly. Please help me!
I will appreciate much your support!
DONE!!!
THE WORKING SCRIPT:
$q = "SELECT UUID() AS uid";
$res = mysql_query($q) or die('q error: '.mysql_error());
$row = mysql_fetch_assoc($res);
// Insert data into mysql
$qry="INSERT INTO $tbl_name1 (ID, REFERENCE, CODE, NAME) VALUES ('".$row['uid']."', '$REFERENCE', '$CODE', '$NAME')";
$result=mysql_query($qry) or die('err 034r '.mysql_error());
$qry2="INSERT INTO $tbl_name2 (PRODUCT) VALUES ('".$row['uid']."')";
$result=mysql_query($qry2) or die('gg2345 '.mysql_error());
Just do SELECT UUID() before you send the INSERTs and put the values into the statements in PHP. Something like this (untested):
$result = mysql_query("SELECT UUID() AS UUID") or die('SQL error: ' . mysql_error());
$row = mysql_fetch_assoc($result);
$UUID = $row["UUID"];
$qry="INSERT INTO $tbl_name1 (ID, REFERENCE, CODE, NAME) VALUES ('$UUID', '$REFERENCE', '$CODE', '$NAME')";
$result=mysql_query($qry);
$qry2="INSERT INTO $tbl_name2 (PRODUCT) VALUES ('$UUID ')"; <--- Here is a problem
$result=mysql_query($qry2)
Another way would be the use of a user-defined variable (see SQL Fiddle):
SET #UUID = (SELECT UUID() AS UUID);
INSERT INTO test1 VALUES(#UUID, "foo");
INSERT INTO test1 VALUES(#UUID, "bar");
Assuming the ID is the table Unique Index you could add before $qry2:
$ID = mysql_insert_id();
Is this possible if I want to insert some data into two tables simultaneously?
But at table2 I'm just insert selected item, not like table1 which insert all data.
This the separate query:
$sql = "INSERT INTO table1(model, serial, date, time, qty) VALUES ('star', '0001', '2010-08-23', '13:49:02', '10')";
$sql2 = "INSERT INTO table2(model, date, qty) VALUES ('star', '2010-008-23', '10')";
Can I insert COUNT(model) at table2?
I have found some script, could I use this?
$sql = "INSERT INTO table1(model, serial, date, time, qty) VALUES ('star', '0001', '2010-08-23', '13:49:02', '10')";
$result = mysql_query($sql,$conn);
if(isset($model))
{
$model = mysql_insert_id($conn);
$sql2 = "INSERT INTO table2(model, date, qty) VALUES ('star', '2010-008-23', '10')";
$result = mysql_query($sql,$conn);
}
mysql_free_result($result);
The simple answer is no - there is no way to insert data into two tables in one command. Pretty sure your second chuck of script is not what you are looking for.
Generally problems like this are solved by ONE of these methods depending on your exact need:
Creating a view to represent the second table
Creating a trigger to do the insert into table2
Using transactions to ensure that either both inserts are successful or both are rolled back.
Create a stored procedure that does both inserts.
Hope this helps
//if you want to insert the same as first table
$qry = "INSERT INTO table (one, two, three) VALUES('$one','$two','$three')";
$result = #mysql_query($qry);
$qry2 = "INSERT INTO table2 (one,two, three) VVALUES('$one','$two','$three')";
$result = #mysql_query($qry2);
//or if you want to insert certain parts of table one
$qry = "INSERT INTO table (one, two, three) VALUES('$one','$two','$three')";
$result = #mysql_query($qry);
$qry2 = "INSERT INTO table2 (two) VALUES('$two')";
$result = #mysql_query($qry2);
//i know it looks too good to be right, but it works and you can keep adding query's just change the
"$qry"-number and number in #mysql_query($qry"")
its cant be done in one statment,
if the tables is create by innodb engine , you can use transaction to sure that the data insert to 2 tables
<?php
if(isset($_POST['register'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$website = $_POST['website'];
if($username == NULL OR $password == NULL OR $email == NULL OR $website == NULL) {
$final_report2.= "ALERT - Please complete all fields!";
} else {
$create_chat_user = mysql_query("INSERT INTO `chat_members` (`id` , `name` , `pass`) VALUES('' , '$username' , '$password')");
$create_member = mysql_query("INSERT INTO `members` (`id`,`username`, `password`, `email`, `website`) VALUES ('','$username','$password','$email','$website')");
$final_report2.="<meta http-equiv='Refresh' content='0; URL=login.php'>";
}
}
?>
you can use something like this. it works.
In general, here's how you post data from one form into two tables:
<?php
$dbhost="server_name";
$dbuser="database_user_name";
$dbpass="database_password";
$dbname="database_name";
$con=mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to the database:' . mysql_error());
$mysql_select_db($dbname, $con);
$sql="INSERT INTO table1 (table1id, columnA, columnB)
VALUES (' ', '$_POST[columnA value]','$_POST[columnB value]')";
mysql_query($sql);
$lastid=mysql_insert_id();
$sql2=INSERT INTO table2 (table1id, table2id, columnA, columnB)
VALUES ($lastid, ' ', '$_POST[columnA value]','$_POST[columnB value]')";
//tableid1 & tableid2 are auto-incrementing primary keys
mysql_query($sql2);
mysql_close($con);
?>
//this example shows how to insert data from a form into multiples tables, I have not shown any security measures