Convert from mysqli to PDO add empty string - php

I'm trying to convert mysqli to PDO but I'm getting one string empty, all the rest is fine.
My code mysqli:
$sql="SELECT uid FROM userprofile WHERE `name` = '$_POST[name]'";
$result=mysqli_query($con,$sql);
if($result&&mysqli_num_rows($result)>0){
$dwID = mysqli_fetch_array($result);
$time=time().'000';
$time1=time();
switch($_POST['t3']){
case ''.$mail_9.'':{
$b=bin2hex($_POST['type1'].','.$_POST['ts1'].','.$_POST['ts2']);
$b1=($_POST['type1'].','.$_POST['ts1'].','.$_POST['ts2']);
mysqli_query($con,"INSERT INTO mail (uid, toUser, title, contents, rewardId, itemIdFlag, status, type, rewardStatus, saveFlag, createTime, reply) VALUES (md5($time), '$dwID[0]','$_POST[titlegift]','$_POST[titlegift]', 0x$b,'1','0','13','0','0','$time','0')")or die('2');
And now I'm trying to converto to PDO like this:
$sql = "SELECT * from userprofile where `uid`='$_POST[name]'";
$query = $dbh2 -> prepare($sql);
$query->execute();
$result=$query->fetch(PDO::FETCH_OBJ);
$cnt=1;
$uid = $query->$result;
$time = time().'000';
$gifttitle = $_POST['gifttitle'];
$b = bin2hex($_POST['type1'].','.$_POST['itemid'].','.$_POST['quantity']);
$sql1 = "INSERT INTO mail (uid, toUser, title, contents, rewardId, itemIdFlag, `status`, `type`, rewardStatus, saveFlag, creatTime, reply) VALUES (md5($time), '$uid', '$_POST[gifttitle]', '$_POST[gifttitle]', 0x$b, '1', '0', '13', '0', '0', '$time', '0')";
$query = $dbh2 -> prepare($sql1);
$query -> execute();
But when I run var_dump (SQL) it add all the fields and only $uid is empty.
Sorry for the code mysqli I know it is a messy.

This is wrong:
$uid = $query->$result;
$result is an object containing the row that was fetched from the table. It's not the name of a property of the $query object.
That should be:
$uid = $result->uid;
You should also use a prepared statement rather than substituting variables into the SQL string.
$sql1 = "INSERT INTO mail (uid, toUser, title, contents, rewardId, itemIdFlag, `status`,
`type`, rewardStatus, saveFlag, creatTime, reply)
VALUES (md5(:time), :uid, :gifttitle, :gifttitle, UNHEX(:rewardid), '1', '0',
'13', '0', '0', :time, '0')";
$query = $dbh2 -> prepare($sql1);
$query->bindParam(':time', $time);
$query->bindParam(':uid', $uid);
$query->bindParam(':rewardid', $b);
$query->bindParam(':gifttitle', $_POST['gifttitle']);
$query->execute();

Related

INSERT into mysql DATABASE Prepared Statments

Can anybody see why this is not inputting into my database..
I did have it working, but now i got the error on mysql A form on this field has more than 1000 fields, but none of them do....
here is the prep statment
$db = new PDO("mysql:host=localhost;dbname=class2", 'root', '');
$query="INSERT INTO `testdata` (`1st name`, `2nd name`, `title`, `info`, `location`, `phone`, `postcode`, `image`, `image2`, `image3`, `image4`, `image5`, `price`, `catagory`, `cond`, `delivery`, `email`, `username`, `youtubevideo`, `paypal`, `facebook`, `twitter`, `feedbackscore`)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
$stat=$db->prepare($query);
$stat->execute(array("$firstname","$lastname","$sellingtitle","$sellinginfo","$town","$phone1","$postcode","$i0url","$i1url","$i2url","$i3url","$i4url","$price","$catagory","$cond","$delivery","","$sellername","$youtubeurl","$paypal","$facebook","$twitter","feedbackscore"));
Your PDO is not prepared correctly.
$database = new PDO("mysql:host=localhost;dbname=class2", 'root', '');
$query = "UPDATE users SET first_name = :first_name, last_name = :last_name
WHERE user_id = :user_id";
$update = $database->prepare($query);
$update->execute([
':first_name' => $_POST['firstname'],
':last_name' => $_POST['lastname'],
':user_id' => $_SESSION['user_id']
]);
$update->fetch();
With PDO you define the keys of the values in the prepare string like :first_name.
So then in the execute function's array, you define the values of these keys.
Hope it helps.

UPDATE table record instead of adding a new record MySQL

Ok .. Here is the thing. I want to list users logged on and change their status when logged out. This works perfect. I created a table for that called tblaudit_users. The existing users I SELECT from a tbl_users table.
What I want, is that if an user already exists in the tblaudit_users table it will UPDATE the LastTimeSeen time with NOW(). But instead of updating that record, it creates a new record. This way the table will grow and grow and I want to avoid that. The code I use for this looks like:
+++++++++++++++++++
$ipaddress = $_SERVER['REMOTE_ADDR'];
if(isset($_SESSION['id'])){
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
$achternaam = $_SESSION['achternaam'];
$district = $_SESSION['district'];
$gemeente = $_SESSION['gemeente'];
$query = $db->prepare("SELECT * FROM tblaudit_users WHERE username = '{$username}' AND active = '1' LIMIT 1");
$query->execute();
foreach($query->fetchAll(PDO::FETCH_OBJ) as $value){
$duplicate = $value->username;
}
if($duplicate != 1){
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district, gemeente, ipaddress, LastTimeSeen, status)
VALUES ('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW(), '1')
");
$insert->execute();
} elseif($duplicate = 1){
$update = $db->prepare("UPDATE tblaudit_users SET LastTimeSeen = NOW(),status = '1' WHERE username = '{$username}'");
$update->execute();
} else {
header('Location: index.php');
die();
}
}
I am lost and searched many websites/pages to solve this so hopefully someone here can help me? Thanks in advance !!
UPDATE:
I've tried the below with no result.
+++++
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district, gemeente, ipaddress, LastTimeSeen, status)
VALUES ('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW(), '1')
ON DUPLICATE KEY UPDATE set LastTimeSeen = NOW(), status = '1'
");
$insert->execute();
Ok. I altered my query and code a little:
$query = $db->prepare("SELECT * FROM tblaudit_users WHERE username = '{$username}' LIMIT 1");
$query->execute();
if($query){
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district, gemeente, ipaddress, LastTimeSeen, status)
VALUES ('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW(), '1')
ON DUPLICATE KEY UPDATE set LastTimeSeen = NOW(), status = '1'
");
$insert->execute();
} else {
header('Location: index.php');
die();
}
}
I also added a UNIQUE key called pid (primary id). Still not working.
Base on http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html, don't use 'set' in update syntax
example from the page:
INSERT INTO table (a,b,c) VALUES (4,5,6) ON DUPLICATE KEY UPDATE c=9;
Several issues:
You test on $query, but that is your statement object, which also will be valid even if you have no records returned from the select statement;
There can be issues accessing a second prepared statement before making sure the previous one is closed or at least has all its records fetched;
There is a syntax error in the insert statement (set should not be there);
For the insert ... on duplicate key update to work, the values you provide must include the unique key;
SQL injection vulnerability;
Unnecessary split of select and insert: this can be done in one statement
You can write your test using num_rows(). To get a correct count call store_result(). Also it is good practice to close a statement before issuing the next one:
$query = $db->prepare("SELECT * FROM tblaudit_users
WHERE username = '{$username}' LIMIT 1");
$query->execute();
$query->store_result();
if($query->num_rows()){
$query->close();
// etc...
However, this whole query is unnecessary when you do insert ... on duplicate key update: there is no need to first check with a select whether that user actually exists. That is all done by the insert ... on duplicate key update statement.
Error in INSERT
The syntax for ON DUPLICATE KEY UPDATE should not have the word SET following it.
Prevent SQL Injection
Although you use prepared statements (good!), you still inject strings into your SQL statements (bad!). One of the advantages of prepared statements is that you can use arguments to your query without actually injecting strings into the SQL string, using bind_param():
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district,
gemeente, ipaddress, LastTimeSeen, status)
VALUES (?, ?, ?, ?, ?, ?, NOW(), '1')
ON DUPLICATE KEY UPDATE LastTimeSeen = NOW(), status = '1'
");
$insert->bind_param("ssssss", $userId, $username, $achternaam,
$district, $gemeente, $ipaddress);
$insert->execute();
This way you avoid SQL injection.
Make sure that user_id has a unique constraint in the tblaudit_users. It does not help to have another (auto_increment) field as primary key. It must be one of the fields you are inserting values for.
The above code no longer uses $query. You don't need it.
I found the issue
if(isset($_SESSION['id'])){
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
$achternaam = $_SESSION['achternaam'];
$district = $_SESSION['district'];
$gemeente = $_SESSION['gemeente'];
$query = $db->prepare("SELECT * FROM tblaudit_users WHERE user_id = '{$userId}' LIMIT 1");
$query->execute();
if($query->rowcount()<1){
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district, gemeente, ipaddress, LastTimeSeen, status)
VALUES ('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW(), '1')
");
$insert->execute();
} elseif($query->rowcount()>0) {
$update = $db->prepare("UPDATE tblaudit_users SET LastTimeSeen = NOW(),status = '1' WHERE user_id = '{$userId}'");
$update->execute();
} else {
header('Location: index.php');
die();
}
}
Instead of using $username in my query, I choose $userId and it works.

Multiple queries & LastInsertId

How wrong is that query? Can I insert multiple queries like that?
Can I use lastInsertId like that?
$pdo = Database::connect();
$dflt = 'DEFAULT';
$query1 = "INSERT INTO utilizador(email, pass, nome, dt_registo, tipo, activo)
VALUES (:email, '$hashed_password', :nome, :dt_registo, :tipo, :activo)";
$stmt = $pdo->prepare($query1);
$stmt->execute();
$insertedid = $pdo->lastInsertId("utilizador");
$query2 ="INSERT INTO aluno(morada, cd_postal, cidade, utilizador_id)
VALUES (:morada, :cpostal, :cidade,'$insertedid')";
$stmt2 = $pdo->prepare($query2);
$stmt2->execute();
$hashed_password = hash( 'sha512', $_POST['password']);
$stmt->bindParam(':email',$_POST['email']);
$stmt->bindParam(':nome',$_POST['nome']);
$stmt->bindParam(':dt_registo',$dflt);
$stmt->bindParam(':tipo',$dflt);
$stmt->bindParam(':activo',$dflt);
$stmt->bindParam(':morada',$_POST['morada']);
$stmt->bindParam(':cpostal',$_POST['cpostal']);
$stmt->bindParam(':cidade',$_POST['cidade']);
if($stmt->execute()){
echo "Product was created.";
}else{
echo "Unable to create product.";
}
Database::disconnect();
}
catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}
I've already been searching but couldn't find how to use both in a query and I already expired all the solutions, not sure which is wrong.
EDIT:
I'm starting to think its more than the query, if someone notice something..
JAVASCRIPT
$(document).on('submit', '#create-aluno-form', function() {
// show a loader img
$('#loader-image').show();
// post the data from the form
$.post("registar.php", $(this).serialize())
.done(function(data) {
// show create product button
$('#create-aluno').show();
showProducts();
});
return false;
});
Most likely your statement fails to insert, Your code is full of problems:
You used prepare statement but yet you put values in the query string
hashed_password is undefined in the first query
You try to bind multiple queries at once
wrong order prepare the first query, execute , then bind the parameters
-$pdo->lastInsertId(); is enough not sure why you pass "utilizador"
Try this approach:
try{
$pdo = Database::connect();
$dflt = 'DEFAULT';
$hashed_password = hash( 'sha512', $_POST['password']);
$query1 = "INSERT INTO utilizador(email, pass, nome, dt_registo, tipo, activo)
VALUES (:email, :pass, :nome, :dt_registo, :tipo, :activo)";
$stmt = $pdo->prepare($query1);
$stmt->bindParam(':email',$_POST['email']);
$stmt->bindParam(':pass',$hashed_password);
$stmt->bindParam(':nome',$_POST['nome']);
$stmt->bindParam(':dt_registo',$dflt);
$stmt->bindParam(':tipo',$dflt);
$stmt->bindParam(':activo',$dflt);
if($stmt->execute()){
//query1 success
$insertedid = $pdo->lastInsertId();
$query2 ="INSERT INTO aluno(morada, cd_postal, cidade, utilizador_id)
VALUES (:morada, :cpostal, :cidade, :utilizador_id)";
$stmt2 = $pdo->prepare($query2);
$stmt2->bindParam(':morada',$_POST['morada']);
$stmt2->bindParam(':cpostal',$_POST['cpostal']);
$stmt2->bindParam(':cidade',$_POST['cidade']);
$stmt2->bindParam(':utilizador_id',$insertedid);
if($stmt2->execute()){
//query2 success
}else{
//query2 failed
}
}else{
//query1 failed
}
Database::disconnect();
}
catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}
Try this....
$query1 = "INSERT INTO utilizador(email, pass, nome, dt_registo, tipo, activo)
VALUES (:email, '$hashed_password', nome, :dt_registo, :tipo, :activo);";
$stmt = $pdo->prepare($query1);
$stmt->execute();
$query2 ="INSERT INTO aluno(morada, cd_postal, cidade, utilizador_id)
VALUES (:morada, :cpostal, :cidade, LAST_INSERT_ID());";
$stmt2 = $pdo->prepare($query2);
$stmt2->execute();
Because insert the query not get last insert id. so separate those queries
You have to use the
mysql_insert_id()
to get the last inserted record's id
I think these will useful to you.
$query = "INSERT INTO utilizador(email, pass, nome, dt_registo, tipo, activo)
VALUES (:email, '$hashed_password', nome, :dt_registo, :tipo, :activo)";
$query_1 = " INSERT INTO aluno(morada, cd_postal, cidade, utilizador_id)
VALUES (:morada, :cpostal, :cidade, mysql_insert_id())";
$stmt = $pdo->prepare($query);
$stmt_1 = $pdo->prepare($query_1);
these will useful to you.
mysql_select_db('test');
mysql_query("INSERT INTO mytable (name) values ('venkatesh')");
printf("Last inserted record has id %d\n", mysql_insert_id());
Thank you.
see here
INSERT INTO questions VALUES(NULL, 'My question');
INSERT INTO answers VALUES(NULL, LAST_INSERT_ID(), 'Answer 1');
INSERT INTO answers VALUES(NULL, LAST_INSERT_ID(), 'Answer 2');
INSERT INTO answers VALUES(NULL, LAST_INSERT_ID(), 'Answer 3');
Now I Have using LAST_INSERT_ID();
INSERT INTO answers VALUES
(NULL, LAST_INSERT_ID(), 'Answer 1') ,
(NULL, LAST_INSERT_ID(), 'Answer 2') ,
(NULL, LAST_INSERT_ID(), 'Answer 3');
OR
also we can try this way
INSERT INTO questions VALUES(NULL, 'My question');
SET #id = (SELECT LAST_INSERT_ID());
INSERT INTO answers VALUES(NULL, #id, 'Answer 1');
INSERT INTO answers VALUES(NULL, #id, 'Answer 2');
INSERT INTO answers VALUES(NULL, #id, 'Answer 3');
It was just an example for you
$query1 = "INSERT INTO utilizador(email, pass, nome, dt_registo, tipo, activo)
VALUES (:email, '$hashed_password', nome, :dt_registo, :tipo, :activo);";
$stmt = $pdo->prepare($query1);
$stmt->execute();
$insertedid = $pdo->lastInsertId("utilizador");
$query2 ="INSERT INTO aluno(morada, cd_postal, cidade, utilizador_id)
Ref link:-http://www.dreamincode.net/forums/topic/169597-pdolastinsertid/
VALUES (:morada, :cpostal, :cidade,'$insertedid'
);";
$stmt2 = $pdo->prepare($query2);
$stmt2->execute();

Use returned ID from SCOPE_IDENTITY in new Query

Right now, this is what I have:
$query = "INSERT INTO COMMENTS VALUES ('$user', '$comment', '$star')";
mssql_query($query, $connection);
$commentIDQuery = "SELECT SCOPE_IDENTITY() AS ins_id";
$CI = mssql_query ($commentIDQuery, $connection);
$commentID = mssql_fetch_row($CI);
$idQuery = "SELECT recipeid FROM t_recipe WHERE recipename = '$recipeName'";
$RID = mssql_query($idQuery, $connection);
$recipeID = mssql_fetch_row($RID);
$rcQuery = "INSERT INTO COMMENT_RECIPE VALUES ('$commentID[0]', '$recipeID[0]')";
mssql_query($rcQuery, $connection);
So how would I get that ins_id?
It adds it to the first table, which is comments, but not the relation table.
Using sql server 2008
What about this......
$query = "DECLARE #NewID INT
INSERT INTO COMMENTS VALUES ('$user', '$comment', '$star');
SELECT #NewID = SCOPE_IDENTITY();
INSERT INTO COMMENTS_RECIPE VALUES (#NewID, '$recipeid')";
$stmt = sqlsrv_query($conn,$query);

using bindParam with PDO

I've been scratching my head over this code for a couple of hours....
Doesn't make sense to me why it doesn't work
$isCorrect =($question->correct_answer == $body->answer) ? 1:0;
// the values are all there.......
// echo $body->question . "\n"; //335
// echo $body->user . "\n"; //51324123
// echo $question->day . "\n"; //0
// echo $isCorrect . "\n"; //0
//but still the below part fails.
$db = getConnection();
$sql = "INSERT INTO `answers` (`id`, `question_id`, `user`, `day`, `is_correct`) VALUES (NULL, ':question', ':user', ':day', :is_correct)";
$stmt = $db->prepare($sql);
$stmt->bindParam(":question_id", $body->question);
$stmt->bindParam(":user", $body->user);
$stmt->bindParam(":day", $question->day, PDO::PARAM_INT);
$stmt->bindParam(":is_correct", $isCorrect, PDO::PARAM_INT);
$stmt->execute();
gives this error:
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
I'm counting 4 tokens... what am I missing? Obviously I'm doing something wrong.
Try it like this:
$sql = "INSERT INTO `answers` (`id`, `question_id`, `user`, `day`, `is_correct`)
VALUES
--The :variable shouldn't be surrounded by ''--
(NULL, :question, :user, :day, :is_correct)";
$stmt = $db->prepare($sql);
//The values used in $sql should be the same here, so not :question_id but :question
$stmt->bindParam(":question", $body->question);
$stmt->bindParam(":user", $body->user);
$stmt->bindParam(":day", $question->day, PDO::PARAM_INT);
$stmt->bindParam(":is_correct", $isCorrect, PDO::PARAM_INT);
just don't use bindParam with PDO
as well as named parameters. it will save you a ton of headaches
$db = getConnection();
$sql = "INSERT INTO `answers` VALUES (NULL, ?,?,?,?)";
$data = [$body->question,$body->user,$question->day,$isCorrect];
$stmt = $db->prepare($sql)->execute($data);
change :
$stmt->bindParam(":question_id", $body->question);
to:
$stmt->bindParam(":question", $body->question);
You have use in query :question but binding with wrong key(:question_id).
$stmt->bindParam(":question_id", $body->question);
should be
$stmt->bindParam(":question", $body->question);
This is just a little typo.

Categories