John Davidson

html - How would I make a php if statement update my sql column

0 comments
Message:


I'm trying to give persons over 16 special options on the website I am creating, but I'm struggling to get the PHP to check the age and then change the column to 1 for Yes or 0 for No.


What I've Tried


if ($account['age']>=16) {
echo 'True';
$sql = 'UPDATE accounts SET o16 = 1 WHERE id = ?';
} else {
echo 'False';
$sql = 'UPDATE accounts SET o16 = 0 WHERE id = ?';
};?>

I'm using MariaDB SQL at this moment.
It returns the values true or false but it does not change the value of the column.



My Answer:
You need to actually execute the SQL query in order to update the column in the database. You can use prepared statements to safely pass the ID parameter to the query. Here's an example of how you can do this:

php
if ($account['age'] >= 16) {
echo 'True';
$o16 = 1;
} else {
echo 'False';
$o16 = 0;
}

// Prepare and execute the SQL query
$stmt = $pdo->prepare('UPDATE accounts SET o16 = :o16 WHERE id = :id');
$stmt->execute(['o16' => $o16, 'id' => $account['id']]);


In this example, `$pdo` is your database connection object. Make sure to replace it with your actual database connection variable. This code will update the `o16` column in the `accounts` table based on the age of the person.

Rate this post

5 of 5 based on 4659 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us