Error: INSERT INTO MariaDB - sql

my code:
<?php
$servername = "127.0.0.1";
$database = "";
$username = "";
$password = "";
$conn = mysqli_connect($servername, $username, $password, $database);
if (!$conn) {
die("failed: " . mysqli_connect_error());
}
echo "connect<br>";
$sql = "INSERT INTO test2 (1, 2, 3) VALUES ('1', '2', '3')";
if (mysqli_query($conn, $sql)) {
echo "add";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
i got error:
connect
Error: INSERT INTO test2 (1, 2, 3) VALUES ('1', '2', '3')
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '1, 2, 3) VALUES ('1', '2', '3')' at line 1
how to fix it?

If you name your columns using only numbers, then you'll have to use backticks around them, e.g. to quote them. See the official chapter Identifier Names, which states:
Further rules:
Identifier names may begin with a numeral, but can't only contain
numerals unless quoted.
So, correct would be:
$sql = "INSERT INTO test2 (`1`, `2`, `3`) VALUES ('1', '2', '3')";
Or, if the columns are of type INT (or similar):
$sql = "INSERT INTO test2 (`1`, `2`, `3`) VALUES (1, 2, 3)";

In the first set of parentheses, '1', '2', '3' are expected as column names. I'm thinking you intended these to be values instead.

Related

Nodejs Mysql Insert is adding backslashes to strings and fails

I'm trying to do a simple sql insert using nodejs and express trying various formats I've found online, but this appears to be the accepted way. When I view the error it's adding extra backslashes to the query and failing.
The code:
console.log(request.body);
var post = {uid: request.session.uid, title: request.body.title, created: request.body.createdAt};
connection.query('INSERT INTO projects (uid, title, created) SET ? ', post, function (error, results, fields) {
console.log(error);
});
The first body console.log:
{ title: 'aewgawegr', createdAt: '1574219119301' }
The error message:
sqlMessage:
'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 \'SET `uid` = 1, `title` = \'aewgawegr\', `created` = \'1574219119301\'\' at line 1',
sqlState: '42000',
index: 0,
sql:
'INSERT INTO projects (uid, title, created) SET `uid` = 1, `title` = \'aewgawegr\', `created` = \'1574219119301\' ' }
For reference: https://dev.mysql.com/doc/refman/8.0/en/insert.html
You cannot combine the two usage syntax:
INSERt INTO `table` (column1, ...) VALUES (value1, ...
with
INSERT INTO `table` SET `column1`='value1', ....
You can do something like this instead of passing json object
"INSERT INTO projects (uid, title, created) VALUES (1, 'Michelle', 'Blue Village 1')";
e.g in your case you can use string interpolation:
`INSERT INTO projects (uid, title, created) VALUES ('${request.session.uid}', '${request.body.title}', '${request.body.createdAt}')`;

insert into two tables at the same time

I have to INSERT INTO two tables at once, let's say one table is my client_enquiry and another table is the client_materials.
Until here it's okay, the INSERT command it's working in both tables. And If something bad happens when I'm inserting on the second table (client_materials)? How can I "rool back" if the INSERT command fails on table client_materials?
Basically I have this:
$sql_table1 = "INSERT INTO client_enquiry (reference, date) VALUES ('REF', '2013-05-12')";
$q = $conn->prepare($sql_table1);
$q ->execute();
$Last_ID = $conn->lastInsertId('id_enquiry');
$sql_table2 = "INSERT INTO client_materials (id_client_enquiry,description, date)
VALUES (".$Last_ID."'Description', '2013-05-12')";
$q = $conn->prepare($sql_table2);
$q -> execute();
Do the very rollback you mentioned.
$conn->beginTransaction();
try
{
$sql = "INSERT INTO client_enquiry (reference, date) VALUES (?,?)";
$q = $conn->prepare($sql);
$q ->execute(array('REF', '2013-05-12'));
$Last_ID = $conn->lastInsertId();
$sql_table2 = "INSERT INTO client_materials (id_client_enquiry,description, date)
VALUES (?,?,?)";
$q = $conn->prepare($sql);
$q -> execute(array($Last_ID, 'Description', '2013-05-12'));
$conn->commit();
}
catch (PDOException $e)
{
$conn->rollback();
throw $e;
}
You just need to be sure that engine supports transactions and PDO is set into exception throwing mode

Inserting 2D Values of Array into SQL

Right now, I have looped a form which in the end gives me a 2D Array.
Array 0D
User Arrays 1D
User Fields 2D
Array ( [1] => Array ( [fname] => qweqwe [lname] => qwewqe [email] => qwewqe [age] => wewqe ) [2] => Array ( [fname] => 123123 [lname] => 123123 [email] => 23123 [age] => 23123 ) )
This is an example of what I get when I type in rubbish into my fields.
To check if I could get the values for each form, I used this:
$i = $_POST['number'];
$corporate = $_POST['corporate'];
$x = 1;
print_r($corporate);
while($x <= $i)
{
echo "The first name first name".$corporate[$x]["fname"].".";
}
Using this, I would attain the first name of the first user, followed by the second and so on. This proves that I can get the 2D values from my forms.
What I have to do now is to insert those values into my table. Keep in mind, my 1D contains values of each user. 2D is the values itself.
mysql_query("INSERT INTO students ('fname','lname','email', 'age') VALUES
I have no idea what to put after that. Any help would be appreciated.
You need to add a set of data values to insert. These would be in the form ("Robert","Brown","Robert.Brown#uni.com","34")("Robert","Smith","Robert.Smith#uni.com","33")
What version of PHP are you using?
for php5.3 you could try:
$values = array();
foreach($corporate as $line){
$values[] = "('".implode("','",array_map(function($x){ return addslashes($x); })) . "')";
}
$query = "INSERT INTO students ('fname','lname','email', 'age') VALUES";
$query .= implode($values);
$record = mysql_query($query);
Otherwise, try:
$values = array();
foreach($corporate as $line){
foreach($line as $i=>$item) $line[$i] = addslashes($item);
$values[] = "('".implode("','",$line) . "')";
}
$query = "INSERT INTO students ('fname','lname','email', 'age') VALUES";
$query .= implode($values);
$record = mysql_query($query);
To solve the second part of your problem, you need to edit the table definitions and remove the "NOT NULL" definition that sits on each field. Do you have php my admin on the server? you could do it through that by editing the table and fields, otherwise you could run the sql using ALTER TABLE. Let me know if you want more information on that.
Well, using your query, understanding what it means in depth, I finally got it working.
This is the code that I used:
foreach($corporate as $line)
{
$values[] = "('".implode("','",$line) . "')";
echo "<br />";
print_r($values);
$a = implode(",", $values);
echo $a;
}
$query = "INSERT into students (fname, lname,email,age) VALUES $a";
$sql = mysql_query($query);
This works fine on my database, works like a charm.
However, when I try this on my friends DB or an Online DB, I get an error which requires me to give every field a value. For some reason, it cannot enter NULL values.
I'm trying to figure out why, but the gist of my problem has been solved.
If you know what is causing my error, feel free to comment. Thanks.

How do I save xml to mysql database?

I found this from original link:
http://www.ecb.europa.eu/stats/exchange/eurofxref/html/index.en.html#dev
e.g.
<?php
function StartElement($parser, $name, $attrs) {
if (!empty($attrs['RATE'])) {
echo "1€=".$attrs['RATE']." ".$attrs['CURRENCY']."<br />";
}
}
$xml_parser= xml_parser_create();
xml_set_element_handler($xml_parser, "StartElement", "");
// for the following command you will need file_get_contents (PHP >= 4.3.0)
// and the config option allow_url_fopen=On (default)
xml_parse($xml_parser, file_get_contents ("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"));
xml_parser_free($xml_parser);
?>
then would be look like:
INSERT INTO `curr_table` (`curr_id`, `curr_title`, `Code`, `decimal_place`, `value`) VALUES
(1, 'EURO', 'EUR', '2', 1.3917),
(2, 'Japan Yen', 'JPY', '2', 112.88),
(3, 'Bla..bla', 'BGN', '2', 1.9558),
..............................etc
(20, 'Bla..bla.', 'CZK', '2', 24.575);
Any pointer and samples code would be appreciate and thanks in advance
If you are using MySQL 5.1 or newer, there is an XML support:
http://dev.mysql.com/tech-resources/articles/xml-in-mysql5.1-6.0.html#xml-5.1-in-and-out

MYSQL: Limit Word Length for MySql Insert

every search query is saved in my database, but I want to Limit the Chracterlength for one single word: odisafuoiwerjsdkle --> length too much --> dont write in the database
my actually code is:
$search = $_GET['q'];
if (!($sql = mysql_query ('' . 'SELECT * FROM `history` WHERE `Query`=\'' . $search . '\''))) {
exit ('<b>SQL ERROR:</b> 102, Cannot write history.');
;
}
while ($row = mysql_fetch_array ($sql)) {
$ID = '' . $row['ID'];
}
if ($ID == '')
{
mysql_query ('' . 'INSERT INTO history (Query) values (\'' . $search . '\')');
}
if (!($sql = mysql_query ('SELECT * FROM `history` ORDER BY `ID` ASC LIMIT 1')))
{
exit ('<b>SQL ERROR:</b> 102, Cannot write history.');
;
}
while ($row = mysql_fetch_array ($sql)) {
$first_id = '' . $row['ID'];
}
if (!($sql = mysql_query ('SELECT * FROM `history`')))
{
exit ('<b>SQL ERROR:</b> 102, Cannot write history.');
;
}
One option would be using a trigger in the table. But, if you are expecting a lot of traffic on your search engine it might not scale very well. So, using client side (PHP in your case) constraints might be a better choice.