I'm trying to get the hang of PDO but I'm getting the following error:
Call to a member function execute() on a non-object
Here's my code to update the members table
$firstname = ($_POST['firstname']);
$lastname = ($_POST['lastname']);
$update = query("UPDATE members SET
firstname = '$firstname',
lastname = '$lastname',
WHERE id = '$id'" );
$q = $conn->prepare($update);
$q->execute(array($firstname,$lastname));
What am I doing wrong here ?
Your use of parentheses around your variables makes them true/false which is not your intent. Then, the whole point of using prepared statements is not to directly insert data into your queries, but instead either use ? or :someVariable so they will be properly escaped and can be used for multiple inserts. Try something like the following:
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$id = $_POST['id'];
$update = query("UPDATE members SET firstname = ?, lastname = ? WHERE id = ?");
$q = $conn->prepare($update);
$q->execute(array($firstname,$lastname,$id));
//OR
$update = query("UPDATE members SET firstname = :firstname , lastname = :lastname WHERE id = :id");
$q = $conn->prepare($update);
$q->execute(array('firstname'=>$firstname,'lastname'=>$lastname,'id'=>$id));
You have a comma where you shouldn't have one:
$update = query("UPDATE members SET
firstname = '$firstname',
lastname = '$lastname'
WHERE id = '$id'" );
Should work, though I would use params in the prepared SQL statement.
$update = query("UPDATE members SET
firstname = :FirstName,
lastname = :LastName
WHERE id = :ID" );
$q = $conn->prepare($update);
$q->execute(array(':FirstName' => $firstname, ':LastName' => $lastname, ':ID' => $ID));
the parameters must be a key value array. string key being the associated parameter in the prepared sql.
$q->execute(array(
'firstname' => $firstname,
'lastname' => $lastname
));
and you're missing 'id' parameter
also, the parameters in the query should prefix with a colon
$update = query("UPDATE members SET
firstname = :firstname,
lastname = :lastname
WHERE id = :id" );
Related
The data on the form failed to saved on the database. I cannot find what's wrong here. I already checked the name of the input forms an it is all correct. I'm using PDO
if ($_POST) {
$accountuname = ($_POST['accountuname']);
$accountpassword = ($_POST['accountpassword']);
$accounttype = ($_POST['accounttype']);
$companyname = ($_POST['companyname']);
$companyproduct = ($_POST['companyproduct']);
$companyaddress = ($_POST['companyaddress']);
$companycontactnum = ($_POST['companycontactnum']);
$query = "INSERT INTO user_accounts SET USER_NAME=?, USER_PASS=?, USER_ACC_TYPE=?, COMPANY_NAME=?, COMPANY_PRODUCT=?, COMPANY_ADDRESS=?, COMPANY_CONTACTNUM=?";
$stmt = $conn->prepare($query);
$stmt -> bindParam(1,$accountuname);
$stmt -> bindParam(2,$accountpassword);
$stmt -> bindParam(3,$accounttype);
$stmt -> bindParam(4,$companyname);
$stmt -> bindParam(5,$companyproduct);
$stmt -> bindParam(6,$companyaddress);
$stmt -> bindParam(7,$companycontactnum);
$stmt -> execute();
}else{
header("location:index.php");
}
Change the SQL query from:
INSERT INTO user_accounts SET USER_NAME=?, USER_PASS=?, USER_ACC_TYPE=?, COMPANY_NAME=?, COMPANY_PRODUCT=?, COMPANY_ADDRESS=?, COMPANY_CONTACTNUM=?
To:
INSERT INTO user_accounts (USER_NAME, USER_PASS, USER_ACC_TYPE, COMPANY_NAME, COMPANY_PRODUCT, COMPANY_ADDRESS, COMPANY_CONTACTNUM) VALUES (?, ?, ?, ?, ?, ?, ?)
INSERT INTO syntax.
If you are using mysqli, acording to the documentation, the bind_param (instead of bindParam... maybe you are using a framework?) function expects the first parameter to be a string, instead of an int:
bind_param ( string $types , mixed &$var1 [, mixed &$... ] )
types
A string that contains one or more characters which specify the types
for the corresponding bind variables:
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
You should change the 1,2,3,4... to 'd,s,b' (the variable type), and it should work.
Hope it helps!
You have to specify the binded parameter type, and also your query was incorrect.
Here is the correct version in MySQLi:
$query = "INSERT INTO user_accounts (USER_NAME, USER_PASS, USER_ACC_TYPE, COMPANY_NAME, COMPANY_PRODUCT, COMPANY_ADDRESS, COMPANY_CONTACTNUM) VALUES (?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($query);
$stmt->bindParam("sssssss", $accountuname, $accountpassword, $accounttype, $companyname, $companyproduct, $companyaddress, $companycontactnum);
// Set parameters and execute
$accountuname = $_POST['accountuname'];
$accountpassword = $_POST['accountpassword'];
$accounttype = $_POST['accounttype'];
$companyname = $_POST['companyname'];
$companyproduct = $_POST['companyproduct'];
$companyaddress = $_POST['companyaddress'];
$companycontactnum = $_POST['companycontactnum'];
$stmt->execute();
Here is the correct version in PDO:
$query = "INSERT INTO user_accounts (USER_NAME, USER_PASS, USER_ACC_TYPE, COMPANY_NAME, COMPANY_PRODUCT, COMPANY_ADDRESS, COMPANY_CONTACTNUM) VALUES (:uname, :upass, :utype, :cname, :cproduct, :caddress, :ccontactnum)";
$stmt = $conn->prepare($query);
$stmt->bindParam(':uname', $accountuname);
$stmt->bindParam(':upass', $accountpassword);
$stmt->bindParam(':utype', $accounttype);
$stmt->bindParam(':cname', $companyname);
$stmt->bindParam(':cproduct', $companyproduct);
$stmt->bindParam(':caddress', $companyaddress);
$stmt->bindParam(':ccontactnum', $companycontactnum);
// Set parameters and execute
$accountuname = $_POST['accountuname'];
$accountpassword = $_POST['accountpassword'];
$accounttype = $_POST['accounttype'];
$companyname = $_POST['companyname'];
$companyproduct = $_POST['companyproduct'];
$companyaddress = $_POST['companyaddress'];
$companycontactnum = $_POST['companycontactnum'];
$stmt->execute();
For MYSQLi: In this example I assumed all the posted data are string, otherwise you would have to change the 'sssssss' in the bindParam function.
Read more about prepared statements here
Read more about MySQLi INSERT syntax here
How do i add multiples columns in pdo for update? this is what I am trying to do but I need to update multiple $_POSTS['VARS];
$consulta = $conexao_pdo->prepare('UPDATE user SET nome = ? WHERE id = ?');
$consulta->bindParam(1, $variavel_com_nome);
$consulta->bindParam(2, $id);
if ($consulta->execute()) {
echo 'UPDATED';
}
What is it that is not working in your code? If you need to update multiple columns, you just need to include them in your update statement: update table1 set col1 = ?, col2 = ?, col3 = ? where id = ?; then assign parameter values for each one.
This is how I solved it
$sql = "UPDATE user SET name = :name,
surname = :surname
WHERE username = :username";
//db column and value
$stmt = $conexao_pdo->prepare($sql);
//where clause
$stmt->bindParam(':username', $username);
//add vars to db
$stmt->bindParam(':name', $var);
$stmt->bindParam(':surname', $var);
$stmt->execute();
I'm working on an inbox system. On the front end, it uses jQuery and Ajax so the page doesn't refresh. I've got that part handled. On the back end, there are 3 tables (for now) that get data inserted.
Here is a basic rundown of the relation structures:
conversations:
conversation_id int(11) primary key
conversation_subject varchar(128)
conversations_members:
conversation_id int(11)
user_id int(11)
conversation_last_view int(10)
conversation_deleted int(1)
conversations_messages:
message_id int(11) primary key
conversation_id int(11)
user_id int(11)
message_date timestamp
message_text text
There is an additional problem since the sender_id is always 0, but that will have to be for another question since it's off topic.
The problem lies in the conversations_members table. Everything else gets entered into the conversations and conversations_messages tables. Here is the PHP. The issue is the very last SQL query at the bottom:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include('../inc/connect.php');
if (!isset($_SESSION['username'])) {
session_start();
}
$recipient_username = "";
$sender_id = "";
$a = 0;
$b = 0;
if(isset($_POST['subject'], $_POST['msg_body']) && !empty($_POST['subject']) && !empty($_POST['msg_body'])) {
//get ID of sender
$sender_id_query = "SELECT id FROM `users` WHERE username = ?";
$stmt = $connection->prepare($sender_id_query);
$stmt->bind_param('s', $_SESSION['username']);
$stmt->execute();
$result = mysqli_query($connection, $sender_id_query);
if($result) {
while($row = mysqli_fetch_assoc($result)) {
//$row['id'] = $sender_id; //neither of these work
$sender_id = $connection->insert_id; //Always zero
}
}
$stmt->close();
//get username of recipient
$recipient_name_query = "SELECT * FROM `users`";
$result = mysqli_query($connection, $recipient_name_query);
if($result) {
while($row = mysqli_fetch_assoc($result)) {
$row['username'] = $recipient_username;
}
}
//define post variables
$msg_subject = $_POST['subject'];
$msg_body = $_POST['msg_body'];
$subject = $connection->real_escape_string(htmlentities($msg_subject));
$body = $connection->real_escape_string(htmlentities($msg_body));
$conversation_id = mysqli_insert_id($connection);
//GET RECIPIENT ID
$sql = "SELECT id FROM `users` WHERE username=?";
$stmt = $connection->prepare($sql);
$stmt->bind_param('s', $recipient_username);
$result = mysqli_query($connection, $sql);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$recipient_id = $row['id'];
}
}
$stmt->close();
//INSERT SUBJECT INTO CONVERSATIONS TABLE
$stmt = $connection->prepare("INSERT INTO `conversations` (conversation_subject) VALUES(?)");
$stmt->bind_param('s', $subject);
$stmt->execute();
$stmt->close();
//INSERT THE IDs AND TIMESTAMPS INTO MESSAGES TABLE
$stmt = $connection->prepare("INSERT INTO `conversations_messages` (conversation_id, user_id, message_date, message_text)
VALUES(?, ?, NOW(), ?)");
$stmt->bind_param('iis', $conversation_id, $sender_id, $body);
$stmt->execute();
$stmt->close();
/*
THE FOLLOWING DATA DOES NOT GET INSERTED.....
*/
//INSERT IDs, LAST_VIEWED, AND DELETED INTO MEMBERS TABLE
$stmt = $connection->prepare("INSERT INTO `conversations_members` (conversation_id, user_id, conversation_last_view, conversation_deleted)
VALUES (?, ?, ?, ?)");
$stmt->bind_param('iiii', $conversation_id, $recipient_id, $a, $b);
$stmt->execute();
$stmt->close();
}
I get no errors, and I'm not seeing any typos. Where did I go wrong?
Thanks to the suggestion of additional error checking, it led me to discover what was happening. I completely removed the while loops, and gave each $stmt variable it's own name since I discovered another error after removing the while loops. Every statement after the first was returning a FALSE value since the previous statement wasn't closed. This code works. I get no errors, and it inserts everything into the database as required.
$recipient_username = $_GET['username'];
$username = $_SESSION['username'];
$a = 0;
$b = 0;
//get ID of sender
$sender_id_query = "SELECT id FROM `users` WHERE username = ?";
$stmt = $connection->prepare($sender_id_query);
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($sender_id);
$val = $stmt->fetch()[$sender_id];
$stmt->close();
//define post variables
$msg_subject = $_POST['subject'];
$msg_body = $_POST['msg_body'];
$subject = $connection->real_escape_string(htmlentities($msg_subject));
$body = $connection->real_escape_string(htmlentities($msg_body));
$conversation_id = mysqli_insert_id($connection);
//GET RECIPIENT ID
$recipient_id_query = "SELECT id FROM `users` WHERE username=?";
$stmt2 = $connection->prepare($recipient_id_query);
$stmt2->bind_param('s', $recipient_username);
$stmt2->execute();
$stmt2->bind_result($recipient_id);
$val_2 = $stmt2->fetch()[$recipient_id];
$stmt2->close();
//INSERT SUBJECT INTO CONVERSATIONS TABLE
$stmt3 = $connection->prepare("INSERT INTO `conversations` (conversation_subject) VALUES(?)");
$stmt3->bind_param('s', $subject);
$stmt3->execute();
$stmt3->close();
//INSERT THE IDs AND TIMESTAMPS INTO MESSAGES TABLE
$stmt4 = $connection->prepare("INSERT INTO `conversations_messages` (conversation_id, user_id, message_date, message_text)
VALUES(?, ?, NOW(), ?)");
$stmt4->bind_param('iis', $conversation_id, $sender_id, $body);
$stmt4->execute();
$stmt4->close();
//INSERT IDs, LAST_VIEWED, AND DELETED INTO MEMBERS TABLE
$stmt5 = $connection->prepare("INSERT INTO `conversations_members` (conversation_id, user_id, conversation_last_view, conversation_deleted)
VALUES (?, ?, ?, ?)");
$q = $stmt5->bind_param('iiii', $conversation_id, $recipient_id, $a, $b);
$stmt5->execute();
$stmt5->close();
$schoolinfo = mysqli_prepare($con, "UPDATE table SET firstname=?, lastname=? from school where foreignkey='$id'");
mysqli_stmt_bind_param($schoolinfo,'ss', $firstname, $lastname)
for ($i=0;$i<count($_POST['row']);$i++){
$firstname = mysqli_real_escape_string($con, $_POST['firstname'][$i]);
$lastname = mysqli_real_escape_string($con, $_POST['lastname'][$i]);
mysqli_stmt_execute($schoolinfo);
}
This updates all rows with the same firstname and lastname.
I want to update rows from selection where foreignkey = '$id' and rownumber ='i'
Any queries or subqueries out there?
just remove this from school from your update query and give a name to your table .
like that
$schoolinfo = mysqli_prepare($con, "UPDATE school SET firstname=?, lastname=? where foreignkey='$id'");
you mixed between SELECT and UPDATE.
i dont know if im wrong or , you have binded firstname and lastname before the loop .
try this
$schoolinfo = mysqli_prepare($con, "UPDATE school SET firstname=?, lastname=? WHERE foreignkey='$id'");
for ($i=0;$i<count($_POST['row']);$i++){
$firstname = $_POST['firstname'][$i];
$lastname = $_POST['lastname'][$i];
mysqli_stmt_bind_param($schoolinfo,'ss', $firstname, $lastname)
mysqli_stmt_execute($schoolinfo);
}
Try this:
$schoolinfo = mysqli_prepare($con, "UPDATE school SET firstname=?, lastname=?
WHERE foreignkey=? and rownumber = ?");
mysqli_stmt_bind_param($schoolinfo,'sssi', $firstname, $lastname, $id, $i);
for ($i=0;$i<count($_POST['row']);$i++){
$firstname = $_POST['firstname'][$i];
$lastname = $_POST['lastname'][$i];
mysqli_stmt_execute($schoolinfo);
}
You didn't have rownumber in the query. And it's best to use bind_param for all variables that you're substituting.
mysql_insert_id does not return the last inserted id when i place it inside a function.
im kinda confused why it does not.
here is my code:
function addAlbum($artist,$album,$year,$genre) {
$connection = mysql_connect(HOST,USER,PASS);
$sql = 'INSERT INTO `'.TABLE_ARTIST.'` (artistName) VALUES ("'.$artist.'")';
$resultArtist = mysql_query($sql);
$sql = 'INSERT INTO `'.TABLE_ALBUMS.'` (albumName) VALUES ("'.$album.'")';
$resultAlbums = mysql_query($sql);
$sql = 'INSERT INTO `'.TABLE_GENRE.'` (musicGenre) VALUES ("'.$genre.'")';
$resultGenre = mysql_query($sql);
$sql = 'INSERT INTO `'.TABLE_YEAR.'` (albumYear) VALUES ("'.$year.'")';
$resultYear = mysql_query($sql);
$lastId = mysql_insert_id();
$sql = 'INSERT INTO `'.TABLE_LINK.'` (albumsId,artistId,genreId,yearId) VALUES ("'.$lastId.'","'.$lastId.'","'.$lastId.'","'.$lastId.'")';
$resultLink = mysql_query($sql);
if(!$resultArtist && $resultAlbums && $resultGenre && $resultYear && $resultLink){
echo mysql_error();
}
}
thanks in advance
adam
You are calling mysql_insert_id() once after four separate INSERTs, and using that ID four times for albumsId, artistId, genreId and yearId. That doesn't seem right.
You should also check that your tables are using AUTO_INCREMENT fields. If not, mysql_insert_id() will not return the insert ID. See the docs:
http://www.php.net/manual/en/function.mysql-insert-id.php
I highly recommend that you use prepared statements with mysqli::prepare, perhaps via PDO. It's ultimately simpler and safer. Here's an untested example:
$dsn = 'mysql:dbname=test;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
$dbh = new PDO($dsn, $user, $password);
$stmt_artist = $dbh->prepare(
'INSERT INTO `table_artist` (artistName) VALUES (?)'
);
$stmt_albums = $dbh->prepare(
'INSERT INTO `table_albums` (albumName) VALUES (?)'
);
$stmt_genre = $dbh->prepare(
'INSERT INTO `table_genre` (musicGenre) VALUES (?)'
);
$stmt_year = $dbh->prepare(
'INSERT INTO `table_year` (albumYear) VALUES (?)'
);
$stmt_link = $dbh->prepare(
'INSERT INTO `table_link` (albumsId, artistId, genreId, yearId) '.
'VALUES (?, ?, ?, ?)'
);
$stmt_albums->execute(array( $artist ));
$artist_id = $dbh->lastInsertId();
$stmt_albums->execute(array( $album ));
$album_id = $dbh->lastInsertId();
$stmt_genre->execute(array( $genre ));
$genre_id = $dbh->lastInsertId();
$stmt_year->execute(array( $year ));
$year_id = $dbh->lastInsertId();
$stmt_link->execute(array( $artist_id, $album_id, $genre_id, $year_id ));
You need to call it separately for each insert, and store the result of each call separately. Like this:
$sql = 'INSERT INTO `'.TABLE_ARTIST.'` (artistName) VALUES ("'.$artist.'")';
$resultArtist = mysql_query($sql);
$lastArtistId = mysql_insert_id();
$sql = 'INSERT INTO `'.TABLE_ALBUMS.'` (albumName) VALUES ("'.$album.'")';
$resultAlbums = mysql_query($sql);
$lastAlbumId = mysql_insert_id();
$sql = 'INSERT INTO `'.TABLE_GENRE.'` (musicGenre) VALUES ("'.$genre.'")';
$resultGenre = mysql_query($sql);
$lastGenreId = mysql_insert_id();
$sql = 'INSERT INTO `'.TABLE_YEAR.'` (albumYear) VALUES ("'.$year.'")';
$resultYear = mysql_query($sql);
$lastYearId = mysql_insert_id();
$sql = 'INSERT INTO `'.TABLE_LINK.'` (albumsId,artistId,genreId,yearId) VALUES ("'.$lastAlbumId.'","'.$lastArtistId.'","'.$lastGenreId.'","'.$lastYearId.'")';
Also, it only works if each of tables you're inserting into has AUTO_INCREMENT enabled.
Did you ever try to debug your code?
With echo() (for showing your SQL queries) or var_dump() (for checking the results of e. g. mysql_insert_id(), mysql_query()).
Also check mysql_error().
Furthermore be sure to set the resource identifier in your mysql_*() functions. It's possible to have more than just one open MySQL resource - so be sure to identify the resource.
For example:
$result = mysql_query($SQL, $connection);
$lastInsertID = mysql_insert_id($connection);
And - it's very important to know that mysql_insert_id() just works with tables which have an AUTO_INCREMENT-field.
And what's also interesting with your code: you call mysql_insert_id solely after the last of 5 queries. Is this really wanted? So you only receive the ID of your last INSERT query.