PHP Script:
<?php
include('connect.php');
if (isset($_POST['project_name'])){
$name = $_POST['project_name'];
$date = $_POST['date'];
$amount = $_POST['amount'];
$curr = $_POST['curr'];
$spec = $_POST['spec'];
$SQL = "INSERT INTO projects (name, date, currency, amount, specifications) VALUES '$name','$date','$amount','$curr','$spec'" or die(mysql_error()."update failed");
$insert = mysql_query($SQL);
if($insert){
echo "Successful";
echo "<BR>";
echo "<a href='insert.php'>Back to main page</a>";
} else {
?>
A HTML FORM HERE
<?php
}
?>
NOTE: The connect.php file is working ok since I've used it before on other scripts but on the same server.
Every time I try to submit the form (method = post), I get this 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 ''sad','08/13/2013','244','dollars','sdasd'' at line 1
32767
What could be the problem?
While inserting, VALUES for a given row have to be enclosed in parenthesis.
INSERT INTO projects (name, date, currency, amount, specifications) VALUES
('$name','$date','$amount','$curr','$spec')
In order to remember that, you simply have to remember that INSERT allow to add several rows, that's why each row has to be delimited by those parenthesis:
-- Just for the example, insert 3 time the same row
INSERT INTO projects (name, date, currency, amount, specifications) VALUES
('$name','$date','$amount','$curr','$spec'),
('$name','$date','$amount','$curr','$spec'),
('$name','$date','$amount','$curr','$spec');
BTW, please note that using string interpolation to build your query is a major risk of SQL injection. Please see How can I prevent SQL injection in PHP? for the details.
INSERT INTO projects (name, date, currency, amount, specifications) VALUES( '$name','$date','$amount','$curr','$spec'")
Add ( after values
You are forgetting the ( & ) in your insert statement:
$SQL = "INSERT INTO projects (name, date, currency, amount, specifications)
VALUES
('$name','$date','$amount','$curr','$spec')" or die(mysql_error()."update failed");
You should pass the name value like 'sad' not ''sad'. Hope you can find the problem.
Related
I have a problem regarding SQL Query. I have 3 Insert queries in my code.
the first query is with auto-increment ID.
INSERT INTO master_tbl
The second Insert will get the ID from 1st query using LAST_INSERT_ID()function.
INSERT INTO process (id_ref, process_id, hot_cold, temp)
VALUES (LAST_INSERT_ID(), '4', '-', '12')
My problem is, I have third query which needed to use the ID generated in the 1st query as its id_ref also.
When I use the LAST_INSERT_ID(), the ID it gets was the ID of the second query.
Any suggestions on how can I still get the ID in the 1st query to use on 3rd?
You can declare the variable and store the first queries id in that variable and then use it wherever you want.
After first query as you mentioned you are using the separate queries you can try using select to set the `Last insert id` into the variable and then use that variable as below,
select #valuetoUse := LAST_INSERT_ID()
Or Other way is use select the to get the value in your code and then pass that value to insert as all other values. For getting value you can directly fire select
SELECT LAST_INSERT_ID()
then in second query
INSERT INTO process (id_ref, process_id, hot_cold, temp)
VALUES (valuetoUse , '4', '-', '12')
then again in the third query
INSERT INTO thirdtable (id_ref, process_id, hot_cold, temp)
VALUES (valuetoUse , '4', '-', '12')
For more info on how to use user defined variables see here.
Functionality is same as told by #Coder of Code But with PHP
Try This
Create Connection
$conn = new mysqli($servername, $username, $password, $dbname);
First Insert into Table 1
INSERT INTO master_tbl
Then do
$sql = "SELECT MAX(id) as id from master_tbl";
$result = $conn->query($sql);
$row = $result->fetch_array(MYSQLI_NUM);
$latest_id=$row[0];
$sql = "INSERT INTO process (id_ref, process_id, hot_cold, temp)
VALUES ($latest_id,'4','-','12')";
if ($conn->query($sql) === TRUE)
{
echo "New record created successfully";
}
$sql = "INSERT INTO table3 (id_ref , columns list)
VALUES ($latest_id,other fields)";
if ($conn->query($sql) === TRUE)
{
echo "New record created successfully";
}
I'm writing a script to insert data about books into a database.
This is the code that inserts the data
$errors=array();
foreach(array('title','author','publisher','pub_date','isbn','Format','genre','category','bookcase','shelf','user_id') as $key=>$val){
$_REQUEST[$key] = mysqli_real_escape_string($ptah,trim($_REQUEST[$val])) ;
};
$title = $_REQUEST['title'] ; $title = strip_tags($title);
$author = $_REQUEST['author'] ; $author = strip_tags($author);
$publisher = $_REQUEST['publisher'] ; $publisher = strip_tags($publisher);
$pub_date = $_REQUEST['pub_date'] ; $pub_date = strip_tags($pub_date);
$isbn = $_REQUEST['isbn'] ; $isbn = strip_tags($isbn);
$format = $_REQUEST['Format'] ; $format = strip_tags($format);
$genre = $_REQUEST['genre'] ; $genre = strip_tags($genre);
$category = $_REQUEST['category'] ; $category = strip_tags($category);
$bookcase = $_REQUEST['bookcase'] ; $bookcase = strip_tags($bookcase);
$shelf = $_REQUEST['shelf'] ; $shelf = strip_tags($shelf);
$username = $_REQUEST['user_id'] ; $username = strip_tags($username);
# On success, register user
if (empty($errors))
# Insert the user into the database
{
$insert_sql = "INSERT INTO library (title, author, publisher, pub_date, isbn, format, genre, category, bookcase, shelf, time_entered, by) VALUES ( '$title', '$author', '$publisher', '$pub_date', '$isbn', '$format', '$genre', '$category', '$bookcase', '$shelf', NOW(), '$username' )";
mysqli_query($ptah,$insert_sql) or die(mysqli_error($ptah));
mysqli_close($ptah);
exit();
};
?>
On submission, I get the following 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 'by) VALUES ( 'Gently Does It', 'Hunter Alan', 'Robinson', '2010', '1234567890', ' at line 1
This misses out format, genre, category, bookcase, shelf, date entered and by whom completely.
Interestingly, the amount of data to be submitted will vary with the length of individual pieces,
for instance
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 'by) VALUES ( 'The Hundred Year Old Man Who Climbed Out of a Window And Disappear' at line 1
doesn't even finish the title whereas
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 'by) VALUES ( 'a', 'b', 'c', '1234', '1', 'Paperback', 'Fiction', 'Fantasy', 'a1'' at line 1
makes it as far as bookcase.
I'm stumped. Could anyone help please.
BY is a reserved word in MySQL so you should escape it with backticks ` in case you need to use it as a field name .
<...> , time_entered, `by`) <...>
BY is a reserved word in MySQL. In order to use it as an identifier in a query you need to enclose it with backticks:
... time_entered, `by`) VALUES (...
It's generally good practice to always enclose identifiers (column names, table names, etc.) with backticks anyway. It's more explicit to the query engine.
In my table I have an userID that is auto-incremented. In the same row I have an idHash. Is it possible to generate the idHash (simply an MD5 sum) from it directly with the same INSERT statement so that I don't have to SELECT the id, and then UPDATE the idHash again?
Problem is: I do not know the userID before it is being generated (auto-incremented) by MySQL.
Thanks
Frank
PS: I'm using PHP.
PPS: This question is all about a SINGLE INSERT. I know that I can use PHP or other languages to manually select the data and then update it.
I don't believe you can do it within a single INSERT statement.
What you probably could do is use an INSERT trigger, that both determines the new ID, hashes it, and then updates the record.
One solution I can recommend is using the last insert ID instead of re-querying the table. Here is a simplified example:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "INSERT INTO users VALUES (....)";
$mysqli->query($query);
$newUserID = $mysqli->insert_id;
$query = "UPDATE users SET idHash = MD5(userID) WHERE userID = $newUserID";
$mysqli->query($query);
/* close connection */
$mysqli->close();
?>
AFAIK there's no "secure" way for doing this in the same query if you're using auto_increment.
However, if rows are never deleted in your table, you can use this little trick :
insert into mytable (col1, col2, col3, idhash)
values ('', '', '', md5(select max(id) from mytable))
I don't understand why you need to hash the id though, why not use the id directly ?
This seems to work for me:
CREATE TABLE tbl (id INT PRIMARY KEY AUTO_INCREMENT, idHash TEXT);
INSERT INTO tbl (idHash) VALUES (MD5(LAST_INSERT_ID() + 1));
SELECT *, MD5(id) FROM tbl;
Note this will only work on single-row inserts as LAST_INSERT_ID returns the insert ID of the first row inserted.
Performing MD5(column_name) on an auto_increment value does not work as the value has not been generated yet, so it is essentially calling MD5(0).
PHP snippet
<?
$tablename = "tablename";
$next_increment = 0;
$qShowStatus = "SHOW TABLE STATUS LIKE '$tablename'";
$qShowStatusResult = mysql_query($qShowStatus) or die ( "Query failed: " . mysql_error() . "<br/>" . $qShowStatus );
$row = mysql_fetch_assoc($qShowStatusResult);
$next_increment = $row['Auto_increment'];
echo "next increment number: [$next_increment]";
?>
This will get you the next auto-increment and then you can use this in your insert.
Note: This is not perfect (Your method is imperfect as you will effectively have 2 primary keys)
From: http://blog.jamiedoris.com/geek/560/
i got two tables and my environment transaction is allowed...
Table A - ID + Name
Table B - ID + Value A+ Value B+ IDTable A
may i know how to write the query to insert value at once ? hope it can be done within single query...just performance is the highest concern.
mysql_query("BEGIN");
$result_1 = mysql_query("INSERT INTO table_a ('name') values ('Chris')");
if( ! $result_1) {
mysql_query("ROLLBACK");
die(); // or handle the error however you choose
}
$table_1_id = mysql_insert_id();
$result_2 = mysql_query("INSERT INTO table_b ('value_a', 'value_b', 'table_a_id') values ('v1', 'v2', $table_1_id)");
if( ! $result_2) {
mysql_query("ROLLBACK");
die(); // or handle the error however you choose
}
mysql_query("COMMIT");
You can't do insert on different tables with a single query.
insert into tableA (name) values ('name');
set #last = last_insert_id();
insert into tableB (valueA,valueB,idtableA) values ('valueA','valueB',#last);
what is the best method to insert a search query into MySql
and check for double words? (for showing up the last searches and a collection of searches)
maybe something like this:
< ?php
/*------------------------------
Read and save the search query
-------------------------------*/
$querystat = mysql_real_escape_string($_GET['q']);
$insertquery = "INSERT INTO `query` ( `query`) VALUES ( '$querystat');";
mysql_query($insertquery, $db);
}
?>
but how to check for double words?
If you don't like a field to contain duplicated entries, you have to define it as UNIQUE.
Then you would issue your connands just the way you suggested:
$querystat = mysql_real_escape_string($_GET['q']);
$insertquery = "INSERT INTO `query` ( `query`) VALUES ( '$querystat');";
$res = mysql_query($insertquery, $db);
if (!$res) echo 'Insert faild. Most likely query already exists';