This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 9 years ago.
This is the error I am getting.
"Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in on line 188"
What I am trying to do is connect to the database and insert data into the table, but i can't figure out this error.
$tableName = "customer";
$nullStr = "NULL";
$SQLstring = "INSERT INTO $tableName VALUES
('".$nullstr."','".$fname."', '".$lname."','".$address."','".$state."','".$zip."', '".$phone"','".$email"')";
$result = $mysqli->query($SQLstring);
You're missing the string concatenation operator . in a couple of places.
Replace
$SQLstring = "INSERT INTO $tableName VALUES
('".$nullstr."','".$fname."', ".$lname."','".$address."','".$state."','".$zip."','".$phone"','".$email"')";
with
$SQLstring = "INSERT INTO $tableName VALUES
('".$nullStr."','".$fname."', '".$lname."','".$address."','".$state."','".$zip."','".$phone."','".$email."')";
BTW, variable names are case-sensitive. You define $nullStr then try to use $nullstr. I fixed it in the above code.
Use a prepared statement with parameter binding instead. Not only does it make this a lot cleaner, it also avoids SQL injection.
$query = "INSERT INTO $tableName VALUES (NULL, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('sssssss', $fname, $lname, $address, $state,
$zip, $phone, $email);
$stmt->execute();
You are missing some periods. Try this...
$SQLstring = "INSERT INTO $tableName VALUES ('".$nullstr."','".$fname."','".$lname."','".$address."','".$state."','".$zip."','".$phone."','".$email."')";
Related
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 3 years ago.
I'm attempting to setup a query through php to a MySQL database. Within the query string I have placed functions and thus have used the dot (.) operator with string closures as seen below. The issue is that my query is not going through and try as i might I can't seem to make out the error. Thanks for any help in advance. :)
$query = "INSERT INTO `foo` (`ip`, `time`, `date`, `reason`) VALUES ('".strval(getUserIpAddr())."', '".$time."', '".$date."', '".$reason."')";
As you should already be aware, your code has security issues so not going to get into that. I don't see any error handling in your code, so can only assume that is why you are not seeing an error. In order to use PDO, you need the driver loaded on the server so keep that in mind. I will reiterate that you should be using prepared statements, here's an example.
$dsn = 'mysql:host=localhost;dbname=testdb';
$username = 'username';
$password = 'password';
$options = array(
// options that apply to your configuration
);
try {
$db = new PDO($dsn, $username, $password, $options);
$sql = "INSERT INTO foo (`ip`, `time`, `date`, `reason`)
VALUES (:ip, :time, :date, :reason)";
$stmt = $db->prepare($sql);
$stmt->bindValue(':ip', strval(getUserIpAddr()), PDO::PARAM_STR);
$stmt->bindValue(':time', $time, PDO::PARAM_STR);
$stmt->bindValue(':date', $date, PDO::PARAM_STR);
$stmt->bindValue(':reason', $reason, PDO::PARAM_STR);
$stmt->execute();
} catch (PDOException $e) {
echo "Exception: " . $e->getMessage();
}
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 am trying to explode() the $_GET['tri'] variable value
(localhost/index.php?tri=*POST BUS*2017-09-01*13:00:00*NDOLA*lusaka*MWILA KAUNDA*0963454336*) and then directly write the explode values to the DB.
Here is the code:
function x(){
$Conn = new mysqli('127.0.0.1','root','','app');
//connect
if (!$Conn->connect_error) {
//query
$query = "INSERT INTO POST_BUS (service, day, time, from, to, name, phone) VALUES(?, ?, ?, ?, ?, ?, ?)";
//prepare stmt
$stmt = $Conn->prepare($query);
//explode tri
$expl = explode('*', $_GET['tri']);
//categorise
$service = "$expl[1]";
$day = "$expl[2]";
$time = "$expl[3]";
$from = "$expl[4]";
$to = "$expl[5]";
$name = "$expl[6]";
$phone = "$expl[7]";
//dispatch tri
$stmt->bind_param('sssssss','".$service."','".$day."','".$time."','".$from."','".$to."','".$name."','".$phone."');
//exe
if ($stmt->execute()) {
print('success!');
}
else{
die('error');
}
}
else{
print('try later!!!');
}
}
i'm getting this error:
Fatal error: Uncaught Error: Call to a member function bind_param() on boolean in C:\xampp\htdocs\index.php:29 Stack trace: #0 C:\xampp\htdocs\index.php(43): x() #1 {main} thrown in C:\xampp\htdocs\index.php on line 29
Where am I going wrong?
$query = "INSERT INTO POST_BUS(service, day, time, `from`, `to`, name, phone) VALUES(?, ?, ?, ?, ?, ?, ?);";
//prepare stmt
$stmt = $Conn->prepare($query);
if (!$stmt) {
die($Conn->error);
}
from and to are reserved words and should be quoted. for a complete list of reserved words in mysql please visit the following link
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
I know this question is sort of dumb but I can't find out where the problem is I checked it with the codes in documentation and similar codes in stackoverflow but I can't figure out the problem.
this is my code:
if (isset($_POST['buy'])) {
$id = (int) $_POST['id'];
$name = $_POST['name'];
$price = (int) $_POST['price'];
date_default_timezone_set("Europe/London");
$date = date("Y-m-d h:i:sa");
$insquery = "INSERT INTO `purchases` (file_id, file_name, price, date) VALUES ({$id}, '{$name}', {$price}, {$date})";
$insResult = mysqli_query($con, $insquery);
if ($insResult) {
//do sth
} else {
//do sth else
}
I have tested these:
1- the post array is not empty and returns exactly those that I assigned to variables.
2- I have a table called purchases and it configured properly because I insert data in SQL and get it back successfully.
3- I have tried on SQL statement without {} around SQL variables but no luck.
and another question is after the SQL statement done how can I use the OUTPUT Inserted.ID as a variable in PHP?
thanks in advance.
date is a keyword in MySql. So use backtick (`).
INSERT INTO purchases (`file_id`, `file_name`, `price`,
`date`) ...
Instead of using direct substitution values, you could use below methods to avoid sql injection.
Using MySQLi (for MySQL):
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
$stmt->execute();
Please refer How can I prevent SQL-injection in PHP?
Use mysqli::$insert_id for last inserted ID (Docs here)
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 8 years ago.
I'm having a few issues with MySQLi queries. I have read the docs for PHP several times and have encountered the same error. I am new to MySQLi but have used MySQL.
Here is the error I am receiving after submitting the post data:
[22-Mar-2014 23:41:17 UTC] PHP Fatal error: Call to a member function bind_param() on a non-object in /home/ponypwna/public_html/Changelist/cpanel.php on line 32
Here is my code for overviewing:
<?php
$MysqlUsername = "*****";
$MysqlPassword = "*****";
$MysqlHostname = "localhost";
$MysqlDatabase = "ponypwna_mane";
/* Establishing Connection here */
$mysqli = new mysqli($MysqlHostname, $MysqlUsername, $MysqlPassword, $MysqlDatabase) or die("Mysql Error: " . $mysqli->error);
//Did we post it?
if (isset($_POST['insertChange'])) {
#Fetching Post Data
$change = $_POST['change'];
$state = $_POST['state'];
$appliesto = $_POST['appliesto'];
$progress = $_POST['progress'];
$completiondate = $_POST['completiondate'];
$contributor = $_POST['contributor'];
#Preparing Query
$insertChange = $mysqli->prepare("INSERT INTO changelist (change, state, appliesto, progress, completiondate, contributor) VALUES (?, ?, ?, ?, ?, ?)");
$insertChange->bind_param('sssiss', $change, $state, $appliesto, $progress, $completiondate, $contributor);
#Executing Prepared Query
$insertChange->execute();
#Close statement and function
$insertChange->close();
}
?>
We are all dumb :)
Upon second look, I seem to be receiving this error from MySQL
(after adding a few debugging tools I was able to see 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 'change,
state, appliesto, progress, completiondate, contributor) VALUES (?, ?,
?' at line 1
"change" is a reserved keyword in MYSQL. https://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Add `` arround change (it is a good idea to wrap every column name - there are various reserved keywords):
$insertChange = $mysqli->prepare("INSERT INTO changelist (`change`, state, appliesto, progress, completiondate, contributor) VALUES (?, ?, ?, ?, ?, ?)");
New Answer
It seems the error is being caused due to an error in your sql syntax.
When you do:
$insertChange = $mysqli->prepare("INSERT INTO changelist (change, state, appliesto, progress, completiondate, contributor) VALUES (?, ?, ?, ?, ?, ?)");
and when here is an error in the syntax, $insertChange is set to false and so it has no method called bind_param() as per the documentation here
Return Values
mysqli_prepare() returns a statement object or FALSE if an error occurred.
So a fix would be to copy-past the sql into an phpMyAdmin or whatever and replace the ? with actual data and run it to see if it works. Maybe one of your columns are missing, spelling error?
I've gone over this script like 30 times, and I can't for the life of me find my problem. Here is the code:
function redeem() {
$case = $_POST["case"];
$name = $_POST["name"];
$profession = $_POST["profession"];
$city = $_POST["city"];
$country = $_POST["country"];
$totalpercent = $_POST["totalpercent"];
$pretest = $_POST["pretest"];
$posttest = $_POST["posttest"];
$investigationspercent = $_POST["investigationspercent"];
$timesreset = $_POST["timesreset"];
$creditsspent = $_POST["creditsspent"];
$timescompleted = $_POST["timescompleted"];
//Add the information to the learnent_cases_leaderboard table
$stmt = $this->db->prepare("INSERT INTO learnent_cases_leaderboard (case, name, profession, city, country, totalpercent, pretest, posttest, investigationspercent, creditsspent, timescompleted, timesreset, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)");
$stmt->bind_param("sssssiiiiiii", $case, $name, $profession, $city, $country, $totalpercent, $pretest, $posttest, $investigationspercent, $creditsspent, $timescompleted, $timesreset); //the quotations specify the type of variable;
//See http://php.net/manual/en/mysqli-stmt.bind-param.php for more information on bind_param
$stmt->execute();
$stmt->close();
When I look at the error log, it gives me this error message:
Line 105 is this line:
PHP Fatal error: Call to a member function bind_param() on a non-object on line 105
Code:
$stmt->bind_param("sssssiiiiiii", $case, $name, $profession, $city, $country, $totalpercent, $pretest, $posttest, $investigationspercent, $creditsspent, $timescompleted, $timesreset);
You never checked that $stmt is an object. In this case, it's more likely to be FALSE, which is what PDO::prepare returns when your query has an error in it.
And your query has an error in it, because you did not delimit your field names in backticks and timestamp is a keyword.
Check for errors after invoking functions from 3rd party APIs, and fix your query.
First of; always run your queries in the localhost to see if your query executes without error. Next always make sure your the names of the fields and data types corresponds with what you have in your code