Insert query does't insert data to mysql database table - php

i have a recipe table and ingredient table the primary key of both tables are auto increament and primary key of recipe is foreign key in ingredient. i post data from html to php.Note that my ingredient textboxes are generated dynamically and successfully post the data to php script. posted data is correct when i insert this data to table my query working fine but data is not added to mysql table. my code and output is
$sql = "insert into recipe (rec_id, Name, Overview,category, Time, Image) values ('', '$name','$overview','$category','$time','$TARGET_PATH')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
$rec_id = mysql_insert_id();
and for ingredient
$ingredient = $_POST['ingredient'];
$amount = $_POST['amount'];
$integer = 0;
while (count($ingredient)>$integer) {
if (($ingredient[$integer] <> "") && ($amount[$integer] <> "")){
$sql = "INSERT INTO `cafe`.`ingredients` (`ingredient_id`, `ingredient_name`, `ammount`, `rec_id`,)
VALUES ('', '".$ingredient[$integer]."', '".$amount[$integer]."', '$rec_id')";
mysql_query($sql);
echo $sql."";
}
else{
echo "ingredient number ".($integer+1)." is missing values and cannot be inserted.";
}
$integer = ($integer + 1);
}
when i echo the queries the out put is nsert into recipe (rec_id, Name, Overview,category, Time, Image) values ('', 'demo recipe','no overview','meal','10/12/10 : 13:02:33','http://www.localhost/cafe/pics/demo.gif')
INSERT INTO cafe.ingredients (ingredient_id, ingredient_name, ammount, rec_id,) VALUES ('', 'ingredient one', '3gm', '29')
INSERT INTO cafe.ingredients (ingredient_id, ingredient_name, ammount, rec_id,) VALUES ('', 'ingredient two', '3gm', '29')
INSERT INTO cafe.ingredients (ingredient_id, ingredient_name, ammount, rec_id,) VALUES ('', 'ingredient three', '3gm', '29')
but when i see the mysql table or retriew data from ingredient there is no data in ingredient.

You have an extra , after rec_id.
Remove it, so it looks like
INSERT INTO cafe.ingredients (ingredient_id, ingredient_name, ammount, rec_id) VALUES ('', 'ingredient one', '3gm', '29')
And you will be OK

There seems to be a syntax error in your code:
if (($ingredient[$integer] "") && ($amount[$integer] ""))
^^ ^^
Looks like you are missing a comparison operator.

You might want to verify if you are using a BEGIN call and not committing after INSERT. You can refer to http://www.devarticles.com/c/a/MySQL/Using-Transactions-with-MySQL-4.0-and-PHP/
in that scenario.

When insert doesnt throw exceptions and doesnt insert data there are I think a couple of options
1) you use transaction somewhere and rollback it
2) your select query is bad and data is there, but you just dont select it

remove cafe from the query
$sql = "INSERT INTO ingredients (`ingredient_id`, `ingredient_name`, `ammount`, `rec_id`,)
VALUES ('', '".$ingredient[$integer]."', '".$amount[$integer]."', '$rec_id')";

Related

INSERT INTO runs only 1 time?

Here's my code:
$con=mysqli_connect("localhost","name","pass","bird") ;
$result = mysqli_query($con,"SELECT * FROM bird");
mysqli_query($con,"INSERT INTO 'bird' (`id`, `name`, `latin`, `number`) values (0,'d','cwer','73')");
the first time, I could see the the values were added but when I reloaded, it didn't do any more, is it supposed to be like this ?
So if I want it to run every time I reload, how can I do that?
You probably have a unique constraint against your id column (or another column in that query) and when you try to add a second row using the same ID it is rejected by MySQL.
You should be doing error checking in your code. You should be checking to see how many rows were affected by your insert (using mysqli_affected_rows()) and, if the number is zero, getting the error message from MySQL (using mysqli_error()).
$result = mysqli_query($con,"INSERT INTO 'bird' (`id`, `name`, `latin`, `number`) values (0,'d','cwer','73')");
if (mysqli_affected_rows() === 0) {
echo mysqli_error($con);
}
#DaveChen's comment above is a good solution to your (potential) problem. If it isn't already, make your id column auto increment and then leave it out of your query.
mysqli_query($con,"INSERT INTO 'bird' (`name`, `latin`, `number`) values ('d','cwer','73')");
If your id column is aut_increment and unique: change your code to:
$con=mysqli_connect("localhost","name","pass","bird") ;
$result = mysqli_query($con,"SELECT * FROM bird");
mysqli_query($con,"INSERT INTO 'bird' (`id`, `name`, `latin`, `number`) values ('','d','cwer','73')");

sql query misses out two columns within the database

Ok Hi I have a slightly weird problem that I cannot figure out mysql query posts the uniq_id in the title column instead of its own and the title, blurb and uniq_id end up empty.
to start off with i create a uniq_id in php and then assign this to be a value within a hidden field within a form this is the code:
$uid = uniqid();
/*echo $uid;*/
echo " <input type=\"hidden\" value=\"$uid\" name=\"Uniq_id\"/>";
this is then posted using the form submit button,
then on the next page $_POST catches all of the values and turns them into variables this is the code for that:
$Title = $_POST['Title'];
$Blurb = $_POST['Blurb'];
$Subject = $_POST['cat'];
$Section = $_POST['typ'];
$Principle = $_POST['princ'];
$Verify = $_POST['verification'];
$Career = $_POST['career'];
$Job = $_POST['job'];
$Uniq_id = $_POST['Uniq_id'];
the variables are then used within this page within the sql query bellow which is ment to post these values into the database the function below is the one that is run when you click the submit button
public function addNewRecord($Subject, $Section, $Principle, $Job, $Career, $Title, $Blurb, $Uniq_id)
{
$sql = "INSERT INTO `careersintheclassroom`.`media` (`media_id`, `subject_id`, `section_id`, `principle_id`, `title`, `blurb`, `verified`, `media_uniqid`)
VALUES (NULL, '".$Subject."', '".$Section."', '".$Principle."', '".$Title."', '".$Blurb."', '0', '".$Uniq_id."')"; // sql query
return mysql_query($sql, $this->conn); // connection to database and also getting the results from query
}
when it posts the values to the page with this function it prints the values on a page showing me all the values this is one of them.
INSERT INTO `careersintheclassroom`.`media` (`media_id`, `subject_id`, `section_id`, `principle_id`, `jobrole_id`, `career_id`, `title`, `blurb`, `verified`, `media_uniqid`)
VALUES (NULL, '1', '1', '1', '2', '2', 'Title1', 'Blurb1', '0', '532061df6b80d');File is valid, and was successfully uploaded.
Now in the database it does something strange it posts in the first 4 values correctly then it inserts the Uniq_id into the title doesn't insert anything into blurb then put the correct value into verified and then leave the last column blank to,
What is the type of the verified field?
Try this, notice the quotes around 0:
VALUES (NULL, '".$Subject."', '".$Section."', '".$Principle."', '".$Title."', '".$Blurb."', '"0"', '".$Uniq_id."')"; // sql query
Hi Guys thanks for all of the answers I have figured out what the problem is I have figured out that my syntax for the mysql query was wrong I used phpmyadmin to create the php code and then altered it to fit the functions but this was wrong the code i was using was:
$sql = "INSERT INTO `careersintheclassroom`.`media` (`media_id`, `subject_id`, `section_id`, `principle_id`, `title`, `blurb`, `verified`, `media_uniqid`)
VALUES (NULL, '".$SUBJECT."', '".$SECTION."', '".$Principle."', '".$Title."', '".$Blurb."', '0', '".$Uniq_id."')";
instead the correct code that it should be is
$sql = "INSERT INTO media (media_id, subject_id, section_id, principle_id, title, blurb, verified, media_uniqid)
VALUES ('NULL', '".$Subject."', '".$Section."', '".$Principle."', '".$Title."', '".$Blurb."', '0', '".$Uniq_id."')";
As you can see the columns have got `` around them this is wrong so removing them inserts the details correctly into the columns
Thanks for everything guys you have helped a lot.
Is it possible that the "title" column is configured to insert a guid for every row insert. Check the column definition for title. Also did you verify that the Blurb and media_uniqueid columns values passed on to the function to be inserted are not null/blank for some reason.. Just checking..

How to select the last inserted ID on concatenated values

I'm trying to get the last inserted id of multiple inserted rows.
record_id is auto increment
$sql = "INSERT INTO records (record_id, user_id, status, x) values ";
$varray = array();
$rid = $row['record_id'];
$uid = $row['user_name'];
$status = $row['status'];
$x = $row['x'];
$varray[] = "('$rid', '$uid', '$status', '$x')";
$sql .= implode(',', $varray);
mysql_query($sql);
$sql2 = "INSERT INTO status_logs (id, record_id, status_id, date, timestamp, notes, user_id, x) VALUES";
$varray2[] = "(' ', mysql_insert_id(), '$status', '$uid', '$x')";
$sql2 .= implode(',', $varray2);
mysql_query($sql2);
This is the result:
INSERT INTO records (record_id, user_id, notes, x) values ('', '1237615', 'this is a note', 'active')
INSERT INTO status_logs (log_id, record_id, status_id, date, timestamp, notes, user_id, x) VALUES('', INSERT INTO records (record_id, user_id, notes, x) values ('', '1237615', 'this is a note', 'active')
INSERT INTO status_logs (log_id, record_id, status_id, date, timestamp, notes, user_id, x) VALUES('', mysql_insert_id(), '1', '2013:05:16 00:00:01', '', this is a note'', '1237615', 'active'), '1', '2013:05:16 00:00:01', '', this is a note'', '1237615', 'active')
There is no value for mysql_insert_id().
You're mixing php function mysql_insert_id() and SQL INSERT statement syntax.
Either use MySQL function LAST_INSERT_ID() in VALUES clause of INSERT statement
INSERT INTO records (user_id, notes, x) VALUES('1237615', 'this is a note', 'active');
INSERT INTO status_logs (record_id, status_id, date, timestamp, notes, user_id, x)
VALUES(LAST_INSERT_ID(), '1', ...);
^^^^^^^^^^^^^^^^^
or retrieve the last inserted id by making a separate call to mysql_insert_id() right after first mysql_query(). And then use that value when you as a parameter to your second query.
$sql = "INSERT INTO records (user_id, ...)
VALUES(...)";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error()); //TODO beter error handling
}
$last_id = mysql_insert_id();
// ^^^^^^^^^^^^^^^^^^
$sql2 = "INSERT INTO status_logs (record_id, ...)
VALUES $last_id, ...)";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error()); //TODO beter error handling
}
Note:
You don't need to specify auto_incremented column in column list. Just omit it.
Use at least some sort of error handling in your code
On a side note: Instead of interpolating query strings and leaving it wide open to sql-injections consider to use prepared statements with either mysqli_* or PDO.
Unless I mis-reading your code, you're calling the PHP function mysql_insert_id from within the SQL?
What you need to do is grab that into a PHP variable first, then use the variable in the SQL. Something like this:
// Run the first query
mysql_query($sql);
// Grab the newly created record_id
$recordid= mysql_insert_id();
Then in the second INSERTs just use:
$varray2[] = "(' ', $recordid, '$status', '$uid', '$x')";

MY sql query not working fully

I am using to add data into DB. First i get the values from post and then insert it into table. The problem is that there are total 7 values but only 5 values added and 2 of them not inserted into the table. Here is my code
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] )) {
$degree_title = $_POST['degree_title'];
$degree_year = $_POST['degree_year'];
$uni_name = $_POST['uni_name'];
$degree_level = $_POST['degree_level'];
$major_sub = $_POST['major_sub'];
$run = mysql_query("INSERT INTO `career_fourudb`.`tffeck_employee_edu` (`id`, `employee_id`, `degree`, `year`, `degree_level`, `major_degree`, `uni`)
VALUES (NULL, $eme_uid, $degree_title, $degree_year, $degree_level, $major_sub, $uni_name)");
}
I echo the all values and all values are coming so why they all not inserted into table any idea. Thank
try:
$run = mysql_query("INSERT INTO `career_fourudb`.`tffeck_employee_edu` (`id`, `employee_id`, `degree`, `year`, `degree_level`, `major_degree`, `uni`)
VALUES (NULL, '$eme_uid', '$degree_title', '$degree_year', '$degree_level', '$major_sub', '$uni_name')");
and i would highly recommend:
1) dont use mysql_ its deprecated, use mysqli_*
2) sanitze ALL values in _POST befor using in SQL statements.
if id is autoincrement then you dont need to insert it.
try this
$run = mysql_query("INSERT INTO `career_fourudb`.`tffeck_employee_edu` (`employee_id`, `degree`, `year`, `degree_level`, `major_degree`, `uni`)
VALUES ($eme_uid, $degree_title, $degree_year, $degree_level, $major_sub, $uni_name)");
My guess is that $degree_title and $uni_name doesn't get inserted because they are varchars. In that case you will have to put quotes around these values.
Mysql is kind of "forgiving" in the sence that it does not throw an error when using incorrect types in the sql-statement in relation to the actual type of the column.
Try:
$run = mysql_query("INSERT INTO `career_fourudb`.`tffeck_employee_edu` (`id`, `employee_id`, `degree`, `year`, `degree_level`, `major_degree`, `uni`)
VALUES (NULL, $eme_uid, '$degree_title', $degree_year, $degree_level, $major_sub, '$uni_name')");
As mentioned before id doesn't have to be included (if id-column is autoincremental) in the insert-statement, and you should really learn mysqli or PDO.

How to insert same data into two tables in mysql

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

Categories