Getting an ID for the last inserted value - php

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();

Related

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}";
}

Inserting multiple string into mysql using bind_param

I'm retrieving tweets from the twitter api, which i'm trying to save in my database however i keep getting an error, which i cant seem to fix. i've checked the number of parameters is correct and everything should be okay, so i dont see why i get following error:
Fatal error: Call to a member function bind_param() on a non-object
tweets database:
function retrievePlayerTweets(){
global $con;
$query = $con->prepare("Select players.fullname, players.twitter_user, team.id as teamId FROM players, team WHERE players.teamId = team.id");
$query->execute();
$query->bind_result($fullname, $twitter_user, $teamId);
while ($query->fetch()) {
foreach(retrieveUserTweets($twitter_user) as $twitterData) {
$id = $twitterData['id_str'];
$text = $twitterData['text'];
$name = $twitterData['user']['name'];
$dateString = $twitterData['created_at'];
$favoriteCount = $twitterData['favorite_count'];
$date = date('Y-m-d H:i:s', strtotime($dateString));
$insert_tweet = $con->prepare("INSERT IGNORE INTO tweets (`fullname`, `username`, `text`, `created`, `teamId`, `twitterId`, `favoriteCount`) VALUES (?, ?, ?, ?, ?, ?, ?)");
$insert_tweet->bind_param("ssssisi", $name, $twitter_user, $text, $date, $teamId, $id, $favoriteCount);
$insert_tweet->execute() or die(mysqli_error($con));
}
}
}
The problem is with your $con variable which is not connecting to the database, due to which the methods inside cannot be called.
also it is good pratice to add die() function to print error message after call to the execute function in PDO or mysqli, to see error in query use:
if using PDO:
$insert_tweet->execute() or die(print_r($con->errorInfo()));
if using mysqli:
$insert_tweet->execute() or die(mysqli_error($con));

PHP & MySQLi Insert Query Failed [duplicate]

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?

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?

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