How can I use a condition in PDO object while a query - php

I am trying to Select Data With PDO (+ Prepared Statements)
The following example uses prepared statements.
http://www.w3schools.com/php/showphpfile.asp?filename=demo_db_select_pdo
I need to know how to make a condition to display only the LASTNAME = PETER. I tried like the below, but not working
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests WHERE lastname =PETER");

If you want to prepare and execute use like this
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests WHERE lastname = :lastname");
$result = $stmt->execute(array(':lastname'=>'PETER'));
And if you want to run directly (which is not recommended if 'PETER' is coming from an user input).
$result = $conn->query("SELECT id, firstname, lastname FROM MyGuests WHERE lastname = 'PETER');

The condition being handed to the WHERE clause needs to be single quoted as it is (I presume) a string. So:
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests WHERE lastname = 'PETER'");
Remember if you are going to make this dynamic in future to sanitise your inputs and use some kind of named parameters like so:
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests WHERE lastname = :lastname");
$stmt->execute([':lastname' => 'PETER']); // the string here can be a variable of course

Related

How can I use several SQL SELECT queries as WHERE clauses in php?

$sql = "INSERT into x (y,z,t)
VALUES ((SELECT userID FROM users WHERE username ='".$usersql."'),"
."'"."(SELECT itemID from items WHERE category ='".$category."'),"
."'".$amountdays."')";
Thank you for your time.
You should use PDO or mysqli with prepared statements. Then you can define variables for your values and set them after the query. That makes it more readable and you prevent sql injections in your code.
https://www.php.net/manual/de/pdo.prepared-statements.php
$stmt = $dbh->prepare("INSERT into x (y,z,t)
VALUES (
SELECT userID FROM users WHERE username = :username,
SELECT itemID FROM items WHERE category = :category,
:amountdays
)";
$stmt->bindParam(':username', $username);
$stmt->bindParam(':category', $category);
$stmt->bindParam(':amountdays', $amountdays);
Something like that.
A little bit of formatting will go a long way:
$sql = "INSERT into x
(
y,
z,
t
) VALUES (
(SELECT userID FROM users WHERE username = ?),
(SELECT itemID from items WHERE category = ?),
?
);
";

Combine INSERT INTO SELECT, with DELETE at the same time

I have a button
<button onClick=sAve('save','."$id."']."')>SAVE</button>
Once I click it, I want to use AJAX to pass the parameters to the PHP page to perform the following task to MYSQL:
switch... case "Save":
$sql1 = "INSERT INTO permanent_table (id, user, email)
SELECT id, user, email
FROM temp_table WHERE id='".$_GET['id']."'";
$sql2 = "DELETE FROM temp_table WHERE id='".$_GET['id']."'";
Whereby permanent_table having same structure as temp_table. I tried to run both queries just like that but it is not working, so I guess that is not the right way.
In my case, my question is:
What is the real pro way to use PHP/sql to perform this task?
Is there any way I can simplify/combine it to a single query?
I think this is you want
<button onClick="$.post('/php file name/', {'save','."$id."'}, function(data){});">SAVE</button><br/>
Then you could run some query's in the PHP file.
$sql = $conn->prepare("INSERT INTO `permanent_table` (`id`, `user`, `email`) VALUES(?, ?, ?)";
$sql->bind_param("sss", $_GET['id'], "", "");
$sql->execute();
$sql = $conn->prepare("DELETE FROM `temp_table` WHERE `id`=?");
$sql->bind_param("s", $_GET['id']);
$sql->execute();
$sql = $conn->prepare("SELECT `id`, `user`, `email` FROM `temp_table` WHERE `id`=?");
$sql->bind_param("s", $_GET['id']);
$sql->execute();
//select last so that you can grab the results
Run them on your way (PDO or MYSQL)
I know a lot about query's so feel free to ask something to me!

Insert select MySQL with prepared statements

I am wondering if I need to do this.
To make it more secure, all the things inserted into database is selected from another table with specific clause that is posted from the user.
I use the id for the identity:
$identity = $_POST['id'];
$stmt = $mysqli->prepare ("INSERT into table_one (col_1, col_2, col_3)
VALUES (?,?,?)");
//This is what I use to do
$stmt >bind_param ("sss", $valua, $valueb, $valuec);
//But now I want to that like this
$stmt >bind_param ("sss", SELECT valuea, valueb, valuec FROM ANOTHERtable WHERE id = $identity);
$list->execute();
$list->close();
Is it possible? And how is the correct way to do this?
You dont need to bind the values from your other table. You just need to prepare those for the values that the user provides. You can safely use the existing values.
$stmt = $mysqli->prepare ("INSERT into table_one (col_1, col_2, col_3)
SELECT valuea, valueb, valuec FROM ANOTHERtable WHERE id = ?");
$stmt >bind_param ("i", $identity);
$stmt->execute();

PHP - MySQL find row and replace

what im trying to figure out is how do i find something in my MySQL database and then replacing another row. Example
mysqli_query($con,"INSERT INTO persons (FirstName, LastName, Age)
VALUES ('$_POST[custom]', '$_POST[receiver_email]','$_POST[mc_gross]')");
$result = mysqli_query($con,"SELECT * FROM Persons
WHERE FirstName='bjarne'");
mysqli_query($con,"INSERT INTO persons (LastName)
VALUES ('$_POST[item_name]')");
Here i would like it to find where FirstName is "bjarne" and then replace his LastName with '$_POST[item_name]' in this case.
Try this:
$result = mysqli_query($con,"UPDATE `Persons` SET `LastName`='".$_POST['item_name']."'
WHERE `FirstName`='bjarne'");

How do I conditionally add a clause to my query in PHP?

In my search form I have, value male, value female, and value both. If you select both, I do not wish to have at WHERE the "sex = '$sex'"
Should i do it like this:
if(empty($sex)){ // value empty if you chose "both"
$query = "SELECT firstname, lastname, id, user_name, sex, last_access, bostadsort FROM users WHERE (firstname LIKE '%$firstname%' OR lastname LIKE '%$lastname%')";
}else{
$query = "SELECT firstname, lastname, id, user_name, sex, last_access, bostadsort FROM users WHERE (firstname LIKE '%$firstname%' OR lastname LIKE '%$lastname%') AND sex = '$sex'";
}
Or is there a smart way to write this?
Do never build an SQL string from user input. That's what prepared statements are for. They are secure, perform faster when re-executed and they're easy to use, so use them:
$sql = "
SELECT
firstname, lastname, id, user_name, sex, last_access, bostadsort
FROM
users
WHERE
(firstname LIKE '%'|| ? || '%' OR lastname LIKE '%'|| ? || '%')
AND Sex = CASE ? WHEN 'both' THEN Sex ELSE ? END
";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('ssss', $firstname, $lastname, $sex, $sex);
$result = $stmt->execute();
How about not repeating yourself:
$query = "SELECT firstname, lastname, id, user_name, sex, last_access, bostadsort FROM users WHERE (firstname LIKE '%$firstname%' OR lastname LIKE '%$lastname%')";
if(!empty($sex)){
$query = $query . " AND sex = '$sex'";
}
You could do this:
$sql = "SELECT ...";
if (!empty($gender))
{
$sql .= " AND gender = '$gender'";
}
And make sure to watch for sql injection.

Categories