This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 4 years ago.
// Not working
$stmt = $connection->prepare( "INSERT INTO numbers (homePhone, mobilePhone, officePhone)".
" VALUES ($phone_1,$phone_2,$phone_3)");
$stmt->execute();
// Works
$stmt = $connection->prepare( "INSERT INTO numbers (homePhone, mobilePhone, officePhone)".
" VALUES (?,?,?)");
$stmt->execute([$phone_1, $phone_2, $phone_3]);
When the first one is executed, it prints the error:
Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 1
no such column: blablabla in
C:\Users\zahha\IdeaProjects\icd0007\index.php:78 Stack trace: #0
C:\Users\zahha\IdeaProjects\icd0007\index.php(78):
PDO->prepare('INSERT INTO peo...') #1 {main} thrown in
C:\Users\zahha\IdeaProjects\icd0007\index.php on line 78
The second one works perfectly. What is the problem? Just wondering.
You need quotes around the variables in the first one, to indicate that the values are string literals in SQL.
$stmt = $connection->prepare( "INSERT INTO numbers (homePhone, mobilePhone, officePhone)".
" VALUES ('$phone_1','$phone_2','$phone_3')");
To make the first one work, you should put the variables between '. For example:
$stmt = $connection->prepare( "INSERT INTO numbers (homePhone, mobilePhone, officePhone)".
" VALUES ('$phone_1','$phone_2','$phone_3')");
$stmt->execute();
Or taking them out of the string, like:
$stmt = $connection->prepare( "INSERT INTO numbers (homePhone, mobilePhone, officePhone)".
" VALUES ('".$phone_1."','".$phone_2."','".$phone_3."')");
$stmt->execute();
Related
This question already has answers here:
bind_param problem with binding boolean values
(3 answers)
Closed 1 year ago.
I don't understand why this is happening even though I have classified $verified as a boolean on my bind_param.
$sql = "INSERT INTO users (user_name, email, verified, token, password) VALUES (?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ssbss', $username, $email, $verified, $token, $password);
Given the column name and the error message, I presume the verified column is an integer. However you're binding it as BLOB:
i corresponding variable has type integer
d corresponding variable has type double
s corresponding variable has type string
b corresponding variable is a blob and will be sent in packets
Both i and s should work.
(Reference)
I have a function that does an INSERT:
function insertData($data){
global $dbh;
$sql = sprintf(
"INSERT INTO location " .
"(" .
"data1, " .
"data2, " .
"data3" .
") " .
"VALUES ('%s', '%s', '%s')",
$data['data1'],
$data['data2'],
$data['data3']
);
echo "$sql \n";
$adjusted = $dbh->quote($sql);
$stmt = $dbh->prepare($adjusted);
$stmt->execute();
$lastId = $dbh->lastInsertId();
return $lastId;
}
When the function is called, I get this error:
INSERT INTO location (data1, data2, data3) VALUES ('Blah1', 'Blah2', 'Blah3')
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 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 ''INSERT INTO location (data1, data2, data3) VALUES (\'Bl' at line 1' in /var/www/test/lib/saveData.php:59
Stack trace:
#0 /var/www/test/lib/saveData.php(59): PDO->prepare(''INSERT INTO lo...')
#1 /var/www/test/lib/saveData.php(10): insertData(Array)
If I run the insert directly it works fine.
I can't figure out what PDO does not like about my syntax.
UPDATE:
Is there a significant difference between using the paramaterization
$sql = "INSERT INTO location (data1, data2, data3) VALUES (?, ?, ?)";
or
$sql = "INSERT INTO location (data1, data2, data3) VALUES (:data1, :data2, :data3)";
UPDATE 2
function insertData($data){
global $dbh;
$sql = "INSERT INTO location " .
"(" .
"data1, " .
"data2, " .
"data3, " .
"data4" .
") VALUES (?, ?, ?, ?)";
$stmt = $dbh->prepare($sql);
$stmt->execute($data);
$lastId = $dbh->lastInsertId();
return $lastId;
}
UPDATE 3 - A debrief For the sake of other readers
I was being clever with sprintf() based on an example I picked up somewhere.
Using sprintf() to build the sql statement is not the same as using named or anonymous bind parameters, so I used the '?' bind parameter and everything worked fine.
Also, I am stuck building on an old system for now, so the shorthand [] array notation was also interfering with successful completion of the task.
Thanks for the input to those who responded.
You are not preparing your statement correctly. sprtinf and quote are breaking your query. Get rid of them and pass the values to execute
function insertData($data) {
global $dbh;
$sql = 'INSERT INTO location
(
data1,
data2,
data3
) VALUES (:data1, :data2, :data3)';
$stmt = $dbh->prepare($sql);
$stmt->execute(array(
'data1' => $data['data1'],
'data2' => $data['data2'],
'data3' => $data['data3']
));
$lastId = $dbh->lastInsertId();
return $lastId;
}
Update:
I have added named placeholders, but I am still building the array manually. If you are sure that $data contains exactly the number of items matching your placeholders you can pass it in directly to execute.
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 6 years ago.
$marka = $_POST['marka'];
$model = $_POST['model'];
$godiste = $_POST['godiste'];
$cena = $_POST['cena'];
$query = "INSERT INTO `auto` (`id`, `marka`, `model`, `godiste`, `cena`) VALUES (NULL, '$marka', '$model', '$godiste', '$cena');"
if(mysqli_query($connection,$query)) {
echo "New record created";
} else {
echo "Error: " . $query . "<br>" . mysqli_error($connection);
}
I can't find what is problem here:
Parse error: syntax error, unexpected 'if' (T_IF) in C:\wamp\www\autoplac\forma.php on line 16
Do not stuff user-input values into query strings. The usual reason given is SQL injection -- and that is an important reason. An even better reason is that you can get unexpected syntax errors, because the content of the string interferes with the rest of the query.
It is easy enough to use parameters. Start with mysqli_prepare(). Here is a place in the documentation to start.
You forgot the semicolon AFTER the Double cuote in the query sentence
Missing ; on end of line
$query = "INSERT INTO `auto` (`id`, `marka`, `model`, `godiste`, `cena`) VALUES (NULL, '$marka', '$model', '$godiste', '$cena');"
should be
$query = "INSERT INTO `auto` (`id`, `marka`, `model`, `godiste`, `cena`) VALUES (NULL, '$marka', '$model', '$godiste', '$cena');";
This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 6 years ago.
I've looked around the internet and haven't been able to resolve this issue.
I'm trying to insert a row into a mySQL table using PDO through this function
function newItem($name, $desc, $price, $catID){
echo $name . "\n";
echo $price . "\n";
echo $desc . "\n";
echo $catID . "\n";
$conn = self::connect();
//INSERT Order
$sql = "INSERT INTO catalogue (Name, Price, CatID, Desc)
VALUES ('$name', $price, $catID, '$desc')";
// use exec() because no results are returned
$conn->exec($sql);
}
when i do, i get this error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 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 'Desc) VALUES ('User', 0.00, 3, 'theUser')' at line 1' in C:\xampp\htdocs\classes\catalogue.php:65 Stack trace: #0 C:\xampp\htdocs\classes\catalogue.php(65): PDO->exec('INSERT INTO cat...') #1 C:\xampp\htdocs\classes\main.php(39): Catalogue->newItem('User', 'theUser', '0.00', '3') #2 {main} thrown in C:\xampp\htdocs\classes\catalogue.php on line 65
I can confirm that the self::connect(); method works, and the problem only occurs when i try to insert data into the Desc column.
I've spent a good while trying to sort this issue, however my knowledge of PDO is quite vague....
Can anyone see where I've gone wrong?
the echo's show this:
User 0.00 theUser 3
DESC is a keyword. You have to escape the column Name using backtics or better rename the column.
$sql = "INSERT INTO catalogue (Name, Price, CatID, `Desc`)
VALUES ('$name', $price, $catID, '$desc')";
For more Information about keywords see the official documentation.
Desc is reserved keyword in mysql in must be in backtick https://dev.mysql.com/doc/refman/5.7/en/keywords.html.html and use prepare and bind statement
$sth = $conn->prepare("INSERT INTO catalogue (Name, Price, CatID, `Desc`)
VALUES (:Name, :Price, :CatID, :Desc)");
$sth->bindParam(':Name', $name, PDO::PARAM_STR);
$sth->bindParam(':Price', $price, PDO::PARAM_STR);
$sth->bindParam(':CatID', $catID, PDO::PARAM_INT);
$sth->bindParam(':Desc', $desc, PDO::PARAM_STR);
$sth->execute();
Try this
$sql = "INSERT INTO catalogue (Name, Price, CatID, Desc)
VALUES ('".$name."', $price, $catID, '".$desc."')";
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 7 years ago.
I want to take the POST data from the three form tags and upload variables to mySQL. When I run the PHP on the second page I get a "Parse error: syntax error, unexpected 'VALUES' (T_STRING) in C:\xampp\htdocs\PHPtest\signUpTRUE.php on line 32"
I can try to post the HTML Form Tags and the PHP..
The HTML form tags:
<div id="headingText"><p> New Fan Club Registration</p></div>
<form action="signUpTRUE.php" method="post" >
<div id="firstNameField">First Name:<input type="text" name="fname"></br></div>
<div id="lastNameField">Last Name: <input type="text" name="lname"></br></div>
<div id="emailField">Email: <input type="text" name="email"></br></div>
<div id="checkboxField"><input type="checkbox" name="terms" value="agree" id="checkboxField" required> *Agree to the terms and conditions </input></div>
<button type="submit" value="Submit" id="button">Submit</button>
</form>
Here is the PHP running calls to mySQL:
<?php
$FN = htmlspecialchars($_POST['fname']);
$LN = htmlspecialchars($_POST['lname']);
$EM = htmlspecialchars($_POST['email']);
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "fanClub";
$conn = new mysqli($servername,$username,$password,$dbname);
if ($conn->connect_error) {
die("Connection Failed: " . $conn->connect_error);
}
$sql = "INSERT INTO userInfo (email, firstname, lastname)"
VALUES ($EM, $FN, $LN);
if ($conn->query($sql) === TRUE) {
echo "<p> data enrty has been logged like whoa</p>";
}else {
echo"<p>error in code.</p>";
}
$conn-close();
?>
I get the
"Parse error: syntax error, unexpected 'VALUES' (T_STRING) in C:\xampp\htdocs\PHPtest\signUpTRUE.php on line 32"
when I try to run this.
Thanks a lot for looking at this :D!
$sql = "INSERT INTO userInfo (email, firstname, lastname)"
VALUES ($EM, $FN, $LN);
This line is wrong. It should be:
$sql = "INSERT INTO userInfo (email, firstname, lastname) VALUES ($EM, $FN, $LN)";
Anyways your code is vulnerable to sql injection
The statement
$sql = "INSERT INTO userInfo (email, firstname, lastname)"
VALUES ($EM, $FN, $LN);
should be
$sql = "INSERT INTO userInfo (email, firstname, lastname)
VALUES ($EM, $FN, $LN)";
(Note where the closing quote is.)
Actually, it should be
$sql = "INSERT INTO userInfo (email, firstname, lastname)
VALUES (?, ?, ?)";
and then you can use it as a prepared statement:
$stmt = $conn->prepare($query);
$stmt->bind_param('sss', $EM, $FN, $LN);
$stmt->execute();
The reason why you're seeing that specific error is because on line 32, you're incorrectly calling the close method of your conn class:
$conn-close();
This is missing the closing angle bracket, and should be:
$conn->close();
After you fix this error, you will then most likely see an error for the incorrect SQL formatting as pointed out in the other answers. This will most likely be a function not defined error, as you probably don't have a function called VALUE($a, $b, $c) somewhere.
You have two issues in query
extra double quotes between columns and values.
not using single quotes between string values.
Modified query:
$sql = "INSERT INTO userInfo (email, firstname, lastname) VALUES ('$EM', '$FN', '$LN')";
Side note:
Also check the close function as mentioned in other answer correct your typo error.
The displayed error can be corrected as follows:
$sql = "INSERT INTO userInfo (email, firstname, lastname) VALUES ($EM, $FN, $LN)";
Also please correct the last line as follows:
$conn->close();