I want to select one row of a table and insert in another existing table.
(I use php and MySql. The two tables have the same columns except the id and the timestamp)
I try to make a cart. I want that when someone pays, select all the products of that client and that session from "carret" and insert into "comandes".
The insert - select works if I say for instance WHERE session=4");
This works too: echo session_id(); So I can get the session
But this two things does not work together. I don't understand the problem. What is wrong with my where condition?
mysql_query("INSERT INTO comandes (session,client,producte,preu_comanda,quantitat)
SELECT session,client,producte,preu_unitat,quantitat
FROM carret
WHERE session='".session_id()."'");
I tried too without success: WHERE client='$_SESSION[client]'
I finally find the problem with a simple ";" at the end. I post it because it could help to other php beginners like me.
This works:
mysql_query("INSERT INTO comandes (id_carret,session,client,producte,preu_comanda,quantitat)
SELECT id,session,client,producte,preu_unitat,quantitat
FROM carret
WHERE session='".session_id()."'");
This does not works!! The problem is with the final ";" if after that there is the "or die ...":
mysql_query("INSERT INTO comandes (id_carret,session,client,producte,preu_comanda,quantitat)
SELECT id,session,client,producte,preu_unitat,quantitat
FROM carret
WHERE session='".session_id()."'");
or die("error:".mysql_error());
This works. Now I see that, if there is the final "or die..." I should remove the previous ";"
mysql_query("INSERT INTO comandes (id_carret,session,client,producte,preu_comanda,quantitat)
SELECT id,session,client,producte,preu_unitat,quantitat
FROM carret
WHERE session='".session_id()."'")
or die("error:".mysql_error());
Related
I've been fighting with a bit of code for a week now, not seeing what the heck is wrong...
I have a gaming site I'm trying to build new character sheets for, the form is all done, the action pointing to another page that is strictly the sql for inserting the information into the database. We have good connection, but it is hanging at the second insert statement. The code was working previously, but we had to delete the database and rebuild it, resulting in a rebuild of the insert sql lines.
The first portion of the insert code is:
if($_POST['Submit']=="Submit")
{
$sql="INSERT INTO accounts (log_name,owner,account_type,date_joined) VALUES (\"$_POST[char_name]\",\"$_SESSION[logname]\",\"$_POST[account_type]\",NOW())";
$result = mysql_query($sql)
or die("<p>Couldn't add character.<br/>".mysql_error()." in accounts.<br/>Please send this exact message to <a href='mailto:savvannis#houston-by-night.com'>Savvannis</a> with your character's name.</p>");
echo $result;
echo $_SESSION['logname'];
$sql="INSERT INTO topdata (log_name,char_venue,sub_venue,species,char_name,create_date,gender,age,appage,nature,demeanor,concept,description,web_site,view_pword,sfa) VALUES (\"$_SESSION[logname]\",\"$_POST[char_venue]\",\"$_POST[sub_venue]\",\"$_POST[species]\",\"$_POST[char_name]\",NOW(),\"$_POST[gender]\",\"$_POST[age]\",\"$_POST[appage]\",\"$_POST[nature]\",\"$_POST[demeanor]\",\"$_POST[concept]\",\"$_POST[description]\",\"$_POST[web_site]\"\"$_POST[viewpw]\",\"$_POST[sfa]\")";
$result=mysql_query($sql)
or die ("<p>Could not create character.<br/>".mysql_error()." in topdata.<br/>Please send this exact message to <a href='mailto:savvannis#houston-by-night.com'>Savvannis</a> with your character's name.</p>");
echo $result;
When the information is entered into the form and submit is hit, I get the following:
1
Could not create character.
Column count doesn't match value count at row 1 in topdata.
Please send this exact message to Savvannis with your character's name.
I look at the database and the information is entered into the accounts table, so that statement is working, but it is hanging up on the topdata table. It's not echoing the $_SESSION['logname'] and looking at the database, it's not saving the owner, which should be $_SESSION['logname'], so I'm wondering if that statement is now somehow incorrect??
I can't figure out what the heck is wrong. Any and all help would be greatly appreciated.
You have missed a comma here: \"$_POST[web_site]\"\"$_POST[viewpw]\" in your second insert SQL.
It should be \"$_POST[web_site]\", \"$_POST[viewpw]\"
First off the error message is telling you that there is an unequal number of columns and values in your SQL
Lets have a look at that
INSERT INTO topdata (
log_name,
char_venue,
sub_venue,
species,
char_name,
create_date,
gender,
age,
appage,
nature,
demeanor,
concept,
description,
web_site,
view_pword,
sfa
) VALUES (
\"$_SESSION[logname]\",
\"$_POST[char_venue]\",
\"$_POST[sub_venue]\",
\"$_POST[species]\",
\"$_POST[char_name]\",
NOW(),
\"$_POST[gender]\",
\"$_POST[age]\",
\"$_POST[appage]\",
\"$_POST[nature]\",
\"$_POST[demeanor]\",
\"$_POST[concept]\",
\"$_POST[description]\",
\"$_POST[web_site]\"\"$_POST[viewpw]\",
\"$_POST[sfa]\"
)";
Now by formatting your SQL (which is vulnerable to sql injection) I've noticed a missing comma between web_site and viewpw values
plz suggest me
what i need is ..when i entered 5 in book_no txtbox then insert 5 rows in
database and values goes in book_no column like 1,2,3,4,5,,,,like wise...
plz suggest me what to change in my for loop....
below code works perfect but values not going in sequential order...
$book_no = $_POST['book_no'];
for($row=1;$row<=$book_no;$row++)
{
$insertrow = $database->insertRow("INSERT INTO scheme_master (book_no,created) VALUES (:book_no,:created)",
array(':book_no'=>$book_no,':created'=>$created));
}
Replace this
':book_no'=>$book_no
with this:
':book_no'=>$row
Ok understood, I think you need to set auto increment in mysql to desired value. This would solve your problem?
If not, you can use lastInsertId method from PDO
link
Hey guys im getting really stuck and could use some help,
I have a query that runs like this
$query = sprintf("SELECT TN,point,source FROM table LIMIT ".$_POST['cases']."");
$result = mysql_query($query);
Then in the while loop i am able to echo
echo " ".$row['0']." and ".$row['1']." and ".$row['2']."<br>";
And get the proper result for each $row['']
My problem is when adding these into the insert statement.
mysql_query("INSERT INTO assigned (TN,point,date1,dude,test,row,rows) VALUES (".$row['0'].",".$row['1'].",'$date','$df','$dx','$num',".$row['2'].")");
The only thing holding the queryback is the $row['2'], if i remove and make it '123' it will properly insert row 0 and 1 and the rest of the data. Ive tried almost all combination to get this to work and im having no luck.
Try to add single quotation marks around $row['2'], like this:
mysql_query("INSERT INTO assigned (TN,point,date1,dude,test,row,rows) VALUES (".$row['0'].",".$row['1'].",'$date','$df','$dx','$num','".$row['2']."')");
Im trying to set a variable using sprintf via a Join Query, then update each time this appears in the table using the ID loaded into the query.
The update works fine if I use a slightly different query but one that gives an identical set of results, so have come to the conclusion Im doing something silly.
Here is a selection below:
//below is a simpler version of what I would like to work with the update
$sql=sprintf("SELECT `test`.`id` FROM `test` JOIN `test2` ON (test.agent=test2.user) WHERE `test`.`type`='new' AND `test2`.`note` = 'p';
//this is what works, even though the output (list of test.id) is identical to above
$sql=sprintf("SELECT `id` FROM `test` WHERE `test`.`type`='new' AND `agent`='test.user';
//here is my update that works with the second select
if($ref_id = mysql_one_data($sql)){
$updateSQL= sprintf("UPDATE `test` SET `type`='testdata', `priority`=%s, `note`=%s WHERE `id`=%s;",SQLVal('100', "int"),SQLVal($note, "text"),SQLVal($ref_id, "int"));
$result = mysql_query($updateSQL) or die(mysql_error());
$processed=TRUE; $result="updated";
$count_converted++;
}
Any ideas? I'm at a total loss! As I said both queries give 100% the same output, so the variable produced should be the same right? and so if one update works when it finds a corresponding value the other should too.
i might be doing some idiot mistake, but i could not figure that out. i have some values coming from html and wanna insert into mysql db. problem is, the very same query does not work in regular php file (that includes other queries), but when i try on an independent php file, it does. here is a sample of the code:
$sql15="insert into body
(Article_ID, Article_Title)
values
('$article_id', '".$_POST['Article_Title']."') ";
mysql_query($sql15);
as i mentioned, the very same code works when i just copy this snippet to a new php file, and it works smoothly.. as you see, there are 20+ insert with the same php, because there are 25+ tables, but data is not much. first 14 query and following 7 queries do work by the way.
do you have any ideas?
There are some things to check and do.
Sanitize user input:
"('$article_id', '".mysql_real_escape_string($_POST['Article_Title'])."')";
You might also want to check if the value is what you expect.
Is your $article_id correct for column Article_ID?
Are your table and column names correct?
Check for errors:
$res = mysql_query($sql15);
if (!$res)
echo mysql_errno($link) . ": " . mysql_error($link);
Show us you complete query:
echo $sql15;
First of all i would suggest you to write your insert query like below
$sql15="insert into body SET Article_ID = '$article_id', Article_Title = '".$_POST['Article_Title']."'";
echo $sql15;
mysql_query($sql15);
so that each time when you add new column to database it would be easy for u to change insert query. echo your query and see it in browser. in it seems to o.k then copy it and paste it in SQL section under your phpmyadmin (see you are choosing proper database) and run it. if one row inserted successfully then your query is alright.
I hope this would help you a little.
$sql15="insert into body
(Article_ID, Article_Title)
values
('$article_id', '".$_POST['Article_Title']."') ";
mysql_query($sql15) or die(mysql_error());
use like this u will be get the error. then u will be find the issue
I think using mysql_real_escape_string may solve your problem.I also recommend you to store your form data in a string.
$article_title= mysql_real_escape_string($_POST['Article_Title']);
$sql15="insert into body
(Article_ID, Article_Title)
values
('$article_id', '$article_title') ";
mysql_query($sql15) or die(mysql_error());