PDO queries not working - php

I have a set of PDO statements that do not seem to be working. Basically I am trying to update the "waiting" value in 1 table and then select that same row and insert it into another table.
$statement = $db->prepare("UPDATE waiting SET wait = :status WHERE id = :id");
$statement->bindValue(':status', 0);
$statement->bindParam(':id', $id);
$statement->execute();
$statement = $db->prepare("INSERT INTO approved (fname, lname, student_id, email, type) (SELECT fname, lname, student_id, email, type FROM waiting WHERE id = :id)");
$statement->bindParam(':id', $id);
$statement->execute();
I've also tried setting $statement to null before I do the other query but that didn't work either:
$statement = $db->prepare("UPDATE waiting SET wait = :status WHERE id = :id");
$statement->bindValue(':status', 0);
$statement->bindParam(':id', $id);
$statement->execute();
$statement = null;
$statement = $db->prepare("INSERT INTO approved (fname, lname, student_id, email, type) (SELECT fname, lname, student_id, email, type FROM waiting WHERE id = :id)");
$statement->bindParam(':id', $id);
$statement->execute();
Any ideas why this isn't working?

Your insert query is syntactically wrong. Remove the brackets from around the select and it should work:
INSERT INTO approved (fname, lname, student_id, email, type)
SELECT fname, lname, student_id, email, type FROM waiting WHERE id = :id

Related

How to check if a table exists in MySQL using PHP PDO? [duplicate]

This question already has answers here:
Check if MySQL table exists without using "select from" syntax?
(19 answers)
Closed 5 years ago.
if($count <= 0 ) // IF TABLE DOES NOT EXIST -> CREATE AND INSERT DATA
{
$CREATE_TABLE= "CREATE TABLE $TABLE_NAME LIKE student; INSERT $TABLE_NAME SELECT * FROM student;";
$created = $connect->exec($CREATE_TABLE);
if($created!=FALSE)
{
$SQL = "INSERT INTO $TABLE_NAME (name, roll_number, father_name, dob, gender, address, email, phone, department, program, semester, section) VALUES(:name, :roll_number, :father_name, :dob, :gender, :address, :email, :phone, :department, :program, :semester, :section)";
$pdo_statement = $connect->prepare($SQL);
$pdo_statement->bindparam(':name', $name);
$pdo_statement->bindparam(':roll_number', $roll_number);
$pdo_statement->bindparam(':father_name', $father_name);
$pdo_statement->bindparam(':dob', $dob);
$pdo_statement->bindparam(':gender', $gender);
$pdo_statement->bindparam(':address', $address);
$pdo_statement->bindparam(':email', $email);
$pdo_statement->bindparam(':phone', $phone);
$pdo_statement->bindparam(':department', $department);
$pdo_statement->bindparam(':program', $program);
$pdo_statement->bindparam(':semester', $semester);
$pdo_statement->bindparam(':section', $section);
$result = $pdo_statement->execute();
}
}
else if($count > 0) // IF TABLE EXIST -> INSERT DATA
{
$SQL = "INSERT INTO $TABLE_NAME (name, roll_number, father_name, dob, gender, address, email, phone, department, program, semester, section) VALUES (:name, :roll_number, :father_name, :dob, :gender, :address, :email, :phone, :department, :program, :semester, :section)";
$pdo_statement = $connect->prepare($SQL);
$pdo_statement->bindparam(':name', $name);
$pdo_statement->bindparam(':roll_number', $roll_number);
$pdo_statement->bindparam(':father_name', $father_name);
$pdo_statement->bindparam(':dob', $dob);
$pdo_statement->bindparam(':gender', $gender);
$pdo_statement->bindparam(':address', $address);
$pdo_statement->bindparam(':email', $email);
$pdo_statement->bindparam(':phone', $phone);
$pdo_statement->bindparam(':department', $department);
$pdo_statement->bindparam(':program', $program);
$pdo_statement->bindparam(':semester', $semester);
$pdo_statement->bindparam(':section', $section);
$result = $pdo_statement->execute();
} // ELSE IF ENDS
So i understand you will create the table, if it does not exist and insert data. So call first
$pdo->query("CREATE TABLE $TABLE IF NOT EXISTS;");
It will do nothing, when table exists.
And then insert your data.
$pdo->query("INSERT INTO $TABLE ... ");
No 'if then else' in PHP!
function tableExists($pdo, $table) {
// Try a select statement against the table
// Run it in try/catch in case PDO is in ERRMODE_EXCEPTION.
try {
$result = $pdo->query("SELECT 1 FROM $table LIMIT 1");
} catch (Exception $e) {
// We got an exception == table not found
return FALSE;
}
// Result is either boolean FALSE (no table found) or PDOStatement Object (table found)
return $result !== FALSE;
}

mistake in query or by post method

I am getting result with $id='S%', but not with $id = $id.'%' when recieved $id = 's' by post
$id = $_POST['user_data'];
if($_POST['user_data'].lenght<2)
{
$query = "SELECT id, oauth_provider, first_name, last_name, email, phone, STATUS , picture, link, createdFROM users WHERE first_name LIKE ? ORDER BY id DESC " ;
$id = $id.'%';
echo ''.$id;
$stmt = $conn->prepare($query);
$stmt->bind_param('s', $id);
$stmt->execute();
$result = $stmt->get_result();
echo $result->num_rows;
}
ialready recieved $id= s by post also checked it by echo it.
output when id= $id='S%' :
9
output when id= $id=$id.'%' :
0
Your query seems to be wrong, it should be
$query = "SELECT id, oauth_provider, first_name, last_name, email, phone, STATUS , picture, link, created FROM users WHERE first_name LIKE ? ORDER BY id DESC " ;
and here is a workaround
$variable = mysql_real_escape_string($id);
$query = "SELECT id, oauth_provider, first_name, last_name, email, phone, STATUS , picture, link, created FROM users WHERE first_name LIKE '% $variable' ORDER BY id DESC";

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.

Insert stmt with a Select and additional Params

Is it possible to have a "mixed" SQL Insert like the following?
I want to be able to get one value from another table (that needs a param) and then enter in 2 more params.
$sql = "INSERT INTO tblquestions (userID, questionText, questionAnswer) VALUES (
Select userID FROM tblusers WHERE userEmail = (?),?,?)";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, 'sss', $userEmail, $question, $answer);
$result = mysqli_stmt_execute($stmt);
if (!$result) {
throw new Exception($conn->error);
}
It is unnecessary. Just use insert . . . select:
INSERT INTO tblquestions(userID, questionText, questionAnswer)
Select userID, ?, ?
FROM tblusers
WHERE userEmail = (?);

insert data from select query results with other external/posted variables

how can i insert data from query results and other variables in one insert query?
sample:
$id = $_POST['id'];
$address = $_POST['address'];
$email = $_POST['email'];
$query = "INSERT INTO info_table(fname, lname, address, email) VALUES (SELECT fname, lname, FROM info WHERE id = '$id')";
$result = db->prepare($query);
$result->execute();
how can i insert $address and $email together with the select results variables?
This should do the trick for the query:
INSERT INTO info_table (
fname,
lname,
address,
email
)
SELECT
fname,
lname,
':address',
':email'
FROM
info
WHERE
id = ':id'
You aren't using the prepare right here. You really should bind to the paramters :address, :email, and :id
$result = db->prepare($query);
$result->bindParam(':id', $id, PDO::PARAM_STR);
$result->bindParam(':email', $email, PDO::PARAM_STR);
$result->bindParam(':address', $address, PDO::PARAM_STR);
$result->execute();
Answering precisely to your question:
$query = "INSERT INTO MyInsecureTable (fname, lname, address, email) SELECT fname, lname, '$address', '$email' FROM info WHERE id = '$id'";
But it is scares the . out of me.

Categories