This question already has answers here:
Inserting multiple values into a MySQL at once [duplicate]
(3 answers)
Closed 9 years ago.
Completely stumped. Getting Error as stated in question title, and no idea why. All my coloumns have text names an there is no reference as far as i know in my code to a column named "1". I have had someone modify this slightly to help me out so maybe there is an issue here i am unaware of.
(string)$insert;
if(is_array($_POST['Year'])){
foreach($_POST['Year'] as $k=>$v){
$insert .= "($_POST['Name'][$k], $_POST['Short'][$k], $_POST['Med'][$k], $_POST['Long'][$k], $_POST['VLong'][$k], $_POST['Extreme'][$k], $_POST['LJump'][$k], $_POST['HJump'][$k], $_POST['Shotputt'][$k], $_POST['Discuss'][$k], $_POST['Javelin'][$k], $_POST['Date'][$k], $_POST['Year'][$k]),";
}
$insert = substr_replace($insert ,0,-1);
}else{
$insert .= "($_POST['Name'], $_POST['Short'], $_POST['Med'], $_POST['Long'], $_POST['VLong'], $_POST['Extreme'], $_POST['LJump'], $_POST['HJump'], $_POST['Shotputt'], $_POST['Discuss'], $_POST['Javelin'], $_POST['Date'], $_POST['Year'])";
}
$sql="INSERT INTO results_main
(`Name`, `Short`, `Med`, `Long`, `VLong`, `Extreme`, `LJump`, `HJump`, `Shotputt`, `Discuss`, `Javelin`, `Date`, `Year`)
VALUES
".$insert;
$result = mysql_query($sql) or die(mysql_error());
// close connection
mysql_close($conn);
The reason is because you are wrapping the values with backticks. Values should be wrap with single quotes if they are string literals. MySQL is treating your values as columns because of the backticks around them. Backticks are used for identifiers not string literals. So the rought example would look like this,
INSERT INTO tableName (col1, col2, col3)
VALUES ('hello', 'world', 'stack')
Related
I have 17 columns in my DB
I'm inserting values from different sources. Somewhere I haven't, for example, company/company_info values (I'm setting in PHP FALSE values for relevant variables).
So, I need some kind of PHP INSERT query to insert only not empty variables and columns of certain list.
For example, I could do:
$q = "INSERT INTO `$tname` (`phone`,`location`, `pagelang`, `company`, `company_url`, `phone_no_cc`, `phone_type`, `operator`, `pageviews`, `rating`, `comments_number`, `activity_by_days`, `activity_by_hours`) VALUES (
'$main_number', '$number_advanced_info[location]', '$pagelang', '$company[name]', '$company[site]', '$number_advanced_info[number_no_countrycode]', '$number_advanced_info[phone_type]', '$number_advanced_info[operator]', '$searches_comments[searches]', '$rating', '$searches_comments[comments]', '$history_search', '$daily_history'
);";
With insert of 14 columns and their values.
But sometimes I need to insert less columns/values and let MYSQL set default values for not listed columns. For Example, I want to insert only 5 columns.
$q = "INSERT INTO `$tname` (`phone`,`location`, `pageviews`, `rating`) VALUES (
'$main_number', '$number_advanced_info[location]', '$searches_comments[searches]', '$rating'
);";
Is there some CLASS or any solution like binding values which will automatically build query depending which values are not NULL?
I need some kind of code:
if (!$phone) {
$columns .= "`column_name`," ;
$values .= "value";
}
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 5 years ago.
MySQLi line like this:
$sqlQuery = "INSERT INTO '$this->dbTable' (url, name_surname, phone, city, category) VALUES('$contents[0]', '$contents[1]', '$contents[2]', '$contents[3]', '$contents[4]')";
Not:
$this->dbTable = 'crawler_data';
But above line does not work. MySQL does not accept. When I change line like this:
$sqlQuery = "INSERT INTO crawler_data(url, name_surname, phone, city, category) VALUES('$contents[0]', '$contents[1]', '$contents[2]', '$contents[3]', '$contents[4]')";
It's working!
How can I set MySQL table name from out?
single or double quotes use for string.when we use '$this->table' it identify like string.change like this.
$sqlQuery = "INSERT INTO $this->dbTable (url, name_surname, phone, city, category) VALUES('$contents[0]', '$contents[1]', '$contents[2]', '$contents[3]', '$contents[4]')";
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP: how to get last inserted ID of a table?
This is my query for inserting a new post into the posts table (PHP/mysql). Can I return the post_id for the post just inserted in the same statement? I need the post_id for insertion into another table.
mysql_query("INSERT INTO `posts` (`post_id`, `date`, `title`, `content`) VALUES (NULL, NOW(), '$title', '$fileName')");
mysql_query("INSERT INTO `posts` (`date`, `title`, `content`) VALUES (NOW(), '$title', '$fileName')");
$last_inserted = mysql_insert_id(); // return last inserted id
mysql_insert_id() will give you the last ID
This is exactly what the MySQL function last_insert_id() is for. So, essentially the answer is, "no, but kinda". You need to execute an additional query "select last_insert_id()", which will return 1 row, with your ID in it.
I'm using this query (I changed it):
// SQL query
$squl = "INSERT INTO 'messages' ('id','name' ,'email' ,'subject' ,'content','userid') VALUES ( null,'".$name."', '".$mail."', '".$subject."', '".$content."','');";
// mysql query
$query = mysql_query($squl) or die("message query problem: ". mysql_error());
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 ''messages' ('id','name' ,'email' ,'subject' ,'content','userid' )VALUES ( null,'' at line 1
What is causing this?
.``) You used a period here instead of a comma so the function is only receiving 5 columns when it needs 6.
Update:
As the commenter below points out, you've replaced the backticks with quotation marks.
$squl="INSERT INTO `messages` (`id`,`name` ,`email` ,`subject` ,`content`,`userid` )VALUES ( null,'$name', '$mail', '$subject', '$content','');";
(id,name ,email ,subject ,content,userid )
( NULL,".$name.", ".$mail.", ".$subject.", ".$content."**.**``);
you are using '.' instead of ,
Well, that's about the clearest message you get from SQL. You try to insert 5 values into 6 columns.
The problem that there's no comma between the last two values. Instead there's a . which makes the parser think it's only one value.
You are trying to insert into 6 columns:
id
name
email
subject
content
userid
But have only specified 5 values:
NULL
$name
$mail
$subject
$content
You've got a dot where you should have a comma:
".$subject."`, `".$content."`.``);";
Change that last dot to a comma and you should be golden
You've got 6 fields in your fields list, but are inserting only 5 values in your values list. Looks like you've got a . instead of a ,:
`, `".$subject."`, `".$content."`.``
^--- here
As well, there is NO reason to use repeated string concatenation as you are. PHP can insert variables into double-quoted strings quiet easily:
$sql = "INSERT INTO .... (...) VALUES (NULL, '$name', '$mail', '$subject', '$content', '')";
Note that the 'null' value is not quoted. Backticks are there to escape reserved words. If you intend to insert a real database null, then use the bare word null. If you want a literal string 'null' to go in, then quote it normally: 'null'.
You have six fields listed the first set of parentheses and only five fields in VALUES. That's what column count means.
This question already has answers here:
Insert multiple rows with one query MySQL
(5 answers)
Closed 2 years ago.
Is this legal?
$string1= "INSERT INTO....;";
$string1 .= "INSERT INTO....;";
$string1 .= "INSERT INTO....;";
mysql_query($string1) or die(mysql_error());
For what it's worth, and depending on if you're inserting the same data into
the same tables, it's much better to insert multiple values with the one insert
e.g.
INSERT INTO a VALUES (1,23),(2,34),(4,33);
INSERT INTO a VALUES (8,26),(6,29);
No, mysql_query() only allows one query at a time.
You can insert multiple rows like this:
INSERT INTO table (col1, col2)
VALUES (1, 2), (3, 4), (5, 6)
From MySQL dev support MySQL dev forum
INSERT INTO table (artist, album, track, length)
VALUES
("$artist", "$album", "$track1", "$length1"),
("$artist", "$album", "$track2", "$length2"),
("$artist", "$album", "$track3", "$length3"),
("$artist", "$album", "$track4", "$length4"),
("$artist", "$album", "$track5", "$length5");
So insert goes as normal as always:
naming first the table name where we want to insert new row,
followed by naming column names in round brackets (Note: Not needed if you want to insert ALL columns),
followed by VALUES key name and then in round brackets comes the values that you want to insert for new ROW in the above table,
followed by COMMA and then another pair of round brackets with new values for new row in the mentioned table above
and this repeats N-times as long you have the data to insert.
Happy inserting multiple values with ONE insert statement. :)
Copy/paste example within a function and a loop (suppose $ids is an array)
public function duplicateItem($ids)
{
if (isset($ids[0])){ //at least one item
$sqlQuery = "INSERT INTO items (item_id, content) VALUES ";
for($i=0; $i<count($ids); $i++) {
if ($i == count($ids)-1){
$sqlQuery .= "(".$ids[$i][0].", '".$ids[$i][1]."');";
}else{
$sqlQuery .= "(".$ids[$i][0].", '".$ids[$i][1]."'),";
}
}
mysql_query($sqlQuery) or die('Error, insert query failed: '.mysql_error());
}
}
In general, that's valid SQL since each statement ends with a semicolon, but PHP doesn't allow you to send more than one query at a time, in order to protect against SQL injection attacks that might exploit a poorly written script.
You can still use a syntax like:
INSERT INTO foo VALUES ('a1', 'b1'), ('a2', 'b2');
INSERT INTO table (a,b) VALUES (1,2), (2,3), (3,4);
No. They are separate queries, and must be called as such.
// if $data is an array
$sqlQuery ="INSERT INTO tableName(col1, col2) VALUES ";
for($i=0; $i<count($data); $i++) {
$sqlQuery .="(".$data[$i][0].", '".$data[$i][1]."'),";
}
$sqlQuery = rtrim($sqlQuery, ','); // Remove last comma
mysql_query($sqlQuery) or die('Error, insert query failed: '.mysql_error());