inserting explode values into table using prepared statement in PHP [duplicate] - php

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

Related

How do I fix the error when updating information in a MySQL table? [duplicate]

This question already has an answer here:
Is there an error when I try to update information in my table?
(1 answer)
Closed 3 years ago.
I'm having some problems trying to work out how to update a MySql table with my php code. This is the section so far, the code should either update the table or add a new column depending on weather an new column has already been made in the database on that date.
Edit: this is a lot of code, just to give context to what I am trying to do, the part of code throwing the error is shown separately below as well :)
$sql = "SELECT * FROM $username WHERE day=?;";
// Here we initialize a new statement by connecting to the database (dbh.php file)
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
// If there is an error the user is sent to the enter data page again
header("Location: ../enterTodaysData.php?error=sqlerror");
exit();
}
else { //if there are no errors...
mysqli_stmt_bind_param($stmt, "s", $day); //binds the parameters to the statement
mysqli_stmt_execute($stmt); //executes the statement
$result = mysqli_stmt_get_result($stmt); //saves the result of the statement into the result variable
if ($row = mysqli_fetch_assoc($result)) { //if the user HAS already made an entry that day
$sql = "UPDATE $username SET (peakflow1, peakflow2, coughing, tightChest, shortBreath, wheezing, symptomOne, symptomTwo, medication, mood, comments, overall WHERE day) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
// If there is an error the user is sent to the enter data page again
header("Location: ../enterTodaysData.php?error=sqlerror");
exit();
}
else { //if there are no errors...
mysqli_stmt_bind_param($stmt, "iisiiiiiiiiss", $peakflow1, $peakflow2, $coughing, $tightChest, $shortBreath, $wheezing, $symptomOne, $symptomTwo, $medication, $mood, $comments, $overall, $day);
mysqli_stmt_execute($stmt); //executes the statement
echo "<script type='text/javascript'>alert('Data entered successfully!');</script>";
header("Location: ../home.php?sql=success");
exit();
}
}
else{ //if the user has not
$sql = "INSERT INTO $username (day, peakflow1, peakflow2, medication, mood, coughing, tightChest, shortBreath, wheezing, symptomOne, symptomTwo, overall, comments) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"; //the question marks are placeholders
$stmt = mysqli_stmt_init($conn);
//an sql statement is prepared and the database is connected to
if (!mysqli_stmt_prepare($stmt, $sql)) {
// If there is an error the user is sent back to the signup page
header("Location: ../enterTodaysdata.php?error=sqlerror");
exit();
}
else {
//binds the paramaters and data to the statement
mysqli_stmt_bind_param($stmt, "siisiiiiiiiis", $day, $peakflow1, $peakflow2, $medication, $mood, $coughing, $tightChest, $shortBreath, $wheezing, $symptomOne, $symptomTwo, $overall, $comments);
//this executes the prepared statement and send it to the database, this registers the user.
mysqli_stmt_execute($stmt);
//sends the user back to the signup page, with a message confirming that it was a success
echo "<script type='text/javascript'>alert('Data entered successfully!');</script>";
header("Location: ../home.php?sql=success");
exit();
}
}
}
This is the part of code that the error is coming from:
$sql = "UPDATE $username SET (peakflow1, peakflow2, coughing, tightChest, shortBreath, wheezing, symptomOne, symptomTwo, medication, mood, comments, overall WHERE day) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
This is the error I am currently getting:
Fatal error: Uncaught mysqli_sql_exception: 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 '(peakflow1, peakflow2, coughing, tightChest, shortBreath, wheezing, symptomOne, ' at line 1 in C:\Users\MMRUD\Documents\XAMPP\htdocs\AsthmaAssistant\php_code\todaysdata.php:47 Stack trace: #0 C:\Users\MMRUD\Documents\XAMPP\htdocs\AsthmaAssistant\php_code\todaysdata.php(47): mysqli_stmt_prepare(Object(mysqli_stmt), 'UPDATE test SET...') #1 {main} thrown in C:\Users\MMRUD\Documents\XAMPP\htdocs\AsthmaAssistant\php_code\todaysdata.php on line 47
Your update syntax is wrong, it looks like you've confused it with INSERT syntax. Instead of something like this:
SET (Field1, Field2) = (?, ?)
you'd do something like this:
SET Field1 = ?, Field2 = ?

I am attempting to update a row in MySQL from PHP using update query where some paramerters need to be used twice

I am attempting to update a row in my database where the users IP address and email address from an email are the used in the where clause of the query.
public function insert_user_captured_data($userip, $didIclickemaillink, $emailclickedfrom, $fname, $lname, $emailentered, $submitclicked){
$sql = "UPDATE testdata
SET useripclicked = ?,
emailclickedfromhere = ?,
userlinkclicked = ?,
userfnameentered = ?,
userlnameentered = ?,
useremailentered = ?,
usersubmittedform = ?,
timestamp = CURRENT_TIMESTAMP
WHERE useripclicked = ? AND emailclickedfromwhere = ?";
$stmnt = $this->dbConnection->prepare($sql);
$stmnt->bind_param("ssisssiss",$userip,$emailclickedfrom,$didIclickemaillink,$fname,$lname,$emailentered,$submitclicked,$userip,$emailclickedfrom);
$insRes = $stmnt->execute();
if (!$insRes) {
throw new Exception("Error Processing Request: Row Not inserted $stmnt->error", 1);
}
}
I am successful in the initial insert but want to update the second pass to fill in the rows after the user has filled out a contact form. I get the following error (in code tags to stand out)
Fatal error: Uncaught Error: Call to a member function bind_param() on boolean in C:\wamp64\www\example.com\assets\php\database.php:73 Stack trace: #0 C:\wamp64\www\example.com\assets\php\thankyou.php(37): Database->insert_user_captured_data('10.0.2.15', 'jfender#example.com', 'Jesse', 'Fender', 'jfender#example.com', 1) #1 {main} thrown in C:\wamp64\www\example.com\assets\php\database.php on line 73
Additionally removed some of the repeated values that really didn't need to be updated with the following as a result:
public function insert_user_captured_data($userip, $emailclickedfrom, $fname, $lname, $emailentered, $submitclicked){
$sql = "UPDATE testdata
SET userfnameentered = ?,
userlnameentered = ?,
useremailentered = ?,
usersubmittedform = ?,
timestamp = CURRENT_TIMESTAMP
WHERE useripclicked = ? AND emailclickedfromwhere = ?";
$stmnt = $this->dbConnection->prepare($sql);
$stmnt->bind_param("sssiss",$fname,$lname,$emailentered,$submitclicked,$userip,$emailclickedfrom);
$insRes = $stmnt->execute();
if (!$insRes) {
throw new Exception("Error Processing Request: Row Not inserted $stmnt->error", 1);
}
}
But am getting the same error, and printing out the error and stack trace have been no help at all...
What am I doing wrong? I'm currently using PHP 7.1.9, MySQL 5.7.19, and Apache 2.4.17 On a Windows 10 system I am using OOP mysqli, and have been inserting just fine in my table.
Im so Sorry guys... I found the error... it happened in the prepare() and it was due to my entering an erroneous letter in one of the column names. here is the corrected code::
public function insert_user_captured_data($userip, $emailclickedfrom, $fname, $lname, $emailentered, $submitclicked){
$sql = "UPDATE testdata
SET userfnameentered = ?,
userlnameentered = ?,
useremailentered = ?,
usersubmittedform = ?,
timestamp = CURRENT_TIMESTAMP
WHERE useripclicked = ? AND emailclickedfromhere = ?";
$stmnt = $this->dbConnection->prepare($sql);
$stmnt->bind_param("sssiss",$fname,$lname,$emailentered,$submitclicked,$userip,$emailclickedfrom);
$insRes = $stmnt->execute();
if (!$insRes) {
throw new Exception("Error Processing Request: Row Not inserted $stmnt->error", 1);
}
}
Jesse Fender
Nice, prepare returns false when there is an SQL error. To track them easier you can make a quick check. Hope it helps:
if ($stmt = $this->dbConnection->prepare("QUERY")) {
$stmt->bind_param(...);
} else {
echo "Prepare error: {$this->dbConnection->errno} - {$this->dbConnection->error}";
}

Can't get bind_param() working correctly

I'm trying to do a simple insert on my database after retrieving a value from it, I'm following the same procedure to retrieve a value from my database as to insert values in it, but I get the following error:
Fatal error: Uncaught Error: Call to a member function bind_param() on boolean
Here's my code:
$getuid = $mysqli->prepare("SELECT id FROM members WHERE email = ?");
$getuid->bind_param("s", $email);
$getuid->execute();
$getuid->bind_result($uid);
$nombre = $_POST['nombre'];
$direccion = $_POST['direccion'];
$codpost = $_POST['codpost'];
$municipio = $_POST['municipio'];
$estado = $_POST['estado'];
while($getuid->fetch()){
echo("INSERT INTO infoclientes VALUES ($uid, $nombre, $direccion, $codpost, $municipio, $estado)");
$infocte = $mysqli->prepare("INSERT INTO infoclientes VALUES(?, ?, ?, ?, ?, ?)");
$infocte->bind_param("ssssss", $uid, $nombre, $direccion, $codpost, $municipio, $estado);
$infocte->execute();
$infocte->close();
}
$getuid->close();
Apparently, the error comes out from
$infocte->bind_param("ssssss", $uid, $nombre, $direccion, $codpost, $municipio, $estado);
This is the output from the echo before the second bind_param:
INSERT INTO infoclientes VALUES (1, Fernando Cervantes, Av. Pie de la cuesta 2, 76158, Querétaro, Querétaro)
I got it to work! I just moved $getuid->close() to the line before the echo(). I guess it was as #LouisLoudogTrottier mentioned, I was trying to prepare both queries while the same connection was opened.

PHP constant encapsed string php error [duplicate]

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."')";

PHP Fatal error: Call to a member function bind_param()

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

Categories