PHP & MySQLi Insert Query Failed [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 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?

Related

PHP Prepared Statement SQL with where value

I am trying to run this query on an existing row in sql table:
if($stmt = $mysqli->prepare("INSERT INTO 4rounds (player2_name, player2_army1_name, player2_army2_name, player2_army3_name, player2_army4_name, player2_identifier, player2_stage, player2_army1_position, player2_army2_position, player2_army3_position, player2_army4_position) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) WHERE pairing_id = ?")) {
but it returns the error:
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 'WHERE pairing_id = ?' at line 1
The query works without the WHERE clause. I think there is a problem with binding the parameter in this matter and I should use VALUE as well to bind it later but I can't seem to find anything online about binding a param in this manner.
These are the binds I am trying with:
$stmt->bind_param("ssssssssssss", $player2_name, $player2_army1_name, $player2_army2_name, $player2_army3_name, $player2_army4_name, $player2_identifier, $player2_stage, $player2_army1_position, $player2_army2_position, $player2_army3_position, $player2_army4_position, $pairing_id);
INSERT statements don't have WHERE clauses, and I'm not sure why you would want such a thing... Those only exist in SELECT and UPDATE queries, typically.

fatal error in mysqli code when inserting

I have a block of code below which inserts data into database using mysqli and php. The problem is that I am getting a fatal error stating: Fatal error: Cannot pass parameter 2 by reference in ... on line 116
Why is this error appearing and how can I fix the error?
Below is the code:
if ($numrows == 0){
$teacherpassword = md5(md5("j3Jf92".$teacherpassword."D203djS"));
$code = md5(rand());
$insertsql = "
INSERT INTO Teacher
(TeacherId, TeacherForename, TeacherSurname, TeacherEmail, TeacherAlias, TeacherUsername, TeacherPassword, Active, Code)
VALUES
(?, ?, ?, ?, ?, ?, ?, ?, ?)
";
if (!$insert = $mysqli->prepare($insertsql)) {
// Handle errors with prepare operation here
}
$insert->bind_param("sssssssss", '', $getfirstname, $getsurname,
$getemail, $getid, $getuser,
$teacherpassword, '0', $code);
$insert->execute();
if ($insert->errno) {
// Handle query error here
}
$insert->close();
mysqli_stmt::bind_param() takes one string detailing the types of the following arguments, and then a set of references to variables that contain the data.
Only variables may be passed by reference, so you are not allowed to pass a string ('' or '0') to the function. You must put that string in a variable, and then pass that variable.
If you're passing constant values to an INSERT, why not make them the DEFAULT values of those fields and then remove them from the query?

Getting an ID for the last inserted value

I am trying to get the unique ID for the most recently added value to the database. I tried using LastInsertID bu I believe this is not compatible with MySQL (http://www.php.net/manual/en/pdo.lastinsertid.php).
$sql = "INSERT INTO discussion_links (link_url, link_title, link_source, publish_date, link_side, img_link) VALUES (?, ?, ?, ?, ?, ?)";
$sth=$db->prepare($sql);
$sth->execute(array($_POST['OP_link_url'], $_POST['OP_title'], $_POST['OP_source'], $_POST['OP_pub_date'], $_POST['OP_disc_side'], $_POST['OP_img_url']));
$op_link_id = $sth->$db->lastInsertID();
Here I get the error: PHP Catchable fatal error: Object of class PDO could not be converted to string
I also tried doing that last line as:
$op_link_id = $sth->fetch(PDO::lastInsertID);
And
$temp = $sth->fetch(PDO::FETCH_ASSOC);
$temp_op_link_id = $temp['link_id'];
But neither one worked (got some SQLState General Error 2053).
Thanks,
lastInsertID() should be called on PDO instance.
$op_link_id = $sth->$db->lastInsertID();
Should be
$op_link_id = $db->lastInsertID();
Try this
$op_link_id = $db->lastInsertID();

Insert error in mysql/php

I have got this function:
public static function insert_user($user)
{
$con = mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("speakom",$con) or die(mysql_error());
mysql_query("INSERT INTO user (user_ip,user_name,full_name,email_address,password,gender,birthday,banned,role,country)
VALUES('".$user->ip."','".$user->name."','".$user->full_name."','".$user->email."','".$user->password."',".$user->gender.",'".$user->birthday."',".$user->banned.",".$user->role.",'".$user->country."'") or die(mysql_error());
mysql_close($con);
}
And 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 '' at line 2
Where does the error point to ? how do I know where the error is?
You're missing the closing ) from the VALUES ( clause. In general, it's easier to assign your SQL to a variable (which you can output for debugging purposes like this) prior to passing it to mysql_query.
Instead of yelling you should use PDO and prepared statements, here's the answer in PDO style:
$con = new PDO('mysql:host=localhost;dbname=speakom', 'root', ''); // optionally add encoding options
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // enable exception throwing
$stmt = $db->prepare('INSERT INTO user (user_ip, user_name, full_name, email_address, password, gender, birthday, banned, role, country)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
$stmt->execute(array(
$user->ip, $user->name, $user->full_name, $user->email, $user->password,
$user->gender, $user->birthday, $user->banned, $user->role, $user->country,
));
Disclaimer didn't test this, but it should give you a good idea :)
would you run
echo "INSERT INTO user (user_ip,user_name,full_name,email_address,password,gender,birthday,banned,role,country) VALUES('".$user->ip."','".$user->name."','".$user->full_name."','".$user->email."','".$user->password."',".$user->gender.",'".$user->birthday."',".$user->banned.",".$user->role.",'".$user->country."'";
and i advise you to use `user` instead of user
VALUES('".$user->ip."','".$user->name."','".$user->full_name."','".$user->email."','".$user->password."',".$user->gender.",'".$user->birthday."',".$user->banned.",".$user->role.",'".$user->country."'"
You are missing ) at the end. By the way, use PDO or mysqli.
Some of the values you want to insert are not in quote, and you missed the closing ) for VALUES. Try this
mysql_query("INSERT INTO user (user_ip,user_name,full_name,email_address,password,gender,birthday,banned,role,country)
VALUES('$user->ip', '$user->name','$user->full_name', '$user->email', '$user->password', '$user->gender', '$user->birthday', '$user->banned', '$user->role', '$user->country')") or die(mysql_error());

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