Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert MySQL code into PDO statement?

Tags:

php

mysql

pdo

I need to change the first if statement into a PDO statement but I'm not sure how to go about it. Please can someone help?

When users submit a form I want their email address to be pulled from the users table on the database into this page on the website, using the numbered $id they are assigned when they sign up.

$table = 'suggestions';
$id = (isset($_SESSION['u_id']) ? $_SESSION['u_id'] : null);

if ( NULL !== $id) {

  $sql = mysqli_query($conn, "SELECT email FROM users WHERE u_id='$id'");
  $fetch = mysqli_fetch_assoc($sql);
  $email = $fetch['email'];

}

$email;
$optionOne = '';
$optionTwo = '';
$suggestions = selectAll($table);


if (isset($_POST['new-suggestion'])) {
  global $conn;

  $id;
  $email;
  $optionOne = $_POST['optionOne'];
  $optionTwo = $_POST['optionTwo'];
  $sql = "INSERT INTO $table (user_id, email, option_1, option_2) VALUES (?, ?, ?, ?)";

  if (!empty($optionOne) && !empty($optionTwo)) {
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('ssss', $id, $email, $optionOne, $optionTwo);
    $stmt->execute();

  } else {
    echo "All options must be entered";
  }
}
like image 215
Alex0720 Avatar asked Dec 04 '20 10:12

Alex0720


People also ask

How to convert MySQL to PDO?

Let's take a look at $dsn : First it defines the driver ( mysql ). Then the database name and finally the host. $dsn = 'sqlsrv:Server=127.0. 0.1;Database=databasename'; $user = 'dbuser'; $password = 'dbpass'; $dbh = new PDO($dsn, $user, $password);

What is PDO query in PHP?

PDO::query() prepares and executes an SQL statement in a single function call, returning the statement as a PDOStatement object.

How to migrate from the MySQL extension to PDO?

Migrate from the MySQL Extension to PDO 1 Installing and Configuring PDO. Once you’ve decided you want to modernize your code, you’ll need to make sure PDO is properly set up and configured. 2 Basic Querying. ... 3 Digging (Slightly) Deeper. ... 4 Summary. ...

Can I use prepared statements with mysqli instead of PDO?

You can use prepared statements with mysqli almost as easily as PDO. Can you please share what you've tried with PDO and issues you ran into? Need to make a PDO connection first php.net/manual/en/pdo.connections.php. Also, again, PDO alone does nothing. The above statement would be just as insecure.

How do I generate PHP code for a MySQL connection?

This simple plugin generates PHP code to create a MySQL connection using PHP's PDO_MySQL extension. The DSN definition depends on the connection type in MySQL Workbench. The part you might want to modify is within the text definition. To generate PHP code for a connection, first install the plugin as follows:

How do I interface with a MySQL database from PHP?

There are actually three ways to interface with a MySQL database from PHP: the first is with the MySQL extension, the second is with the MySQLi extension and the third is with PDO. The MySQL extension is the oldest of the three and was the original option developers used to communicate with MySQL.


1 Answers

Make a connection

Firstly you need to replace your mysqli connection with a PDO one (or at least add the PDO connection alongside the mysqli one!).

// Define database connection parameters
$db_host = "127.0.0.1";
$db_name = "name_of_database";
$db_user = "user_name";
$db_pass = "user_password";


// Create a connection to the MySQL database using PDO
$pdo = new pdo(
    "mysql:host={$db_host};dbname={$db_name}",
    $db_user,
    $db_pass,
    [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_EMULATE_PREPARES => FALSE
    ]
);

Updating your code

Prepared statements with mysqli and PDO

It's almost always better to use prepared statements when putting variable data into an SQL query. Not only is it safer (if the data comes from any sort of user generated input) but it also makes it easier to read, and easier to run multiple times with different values.

Prepared query with mysqli:

$sql   = "SELECT column1, column2 FROM table WHERE column3 = ? AND column4 = ?";
$query = $mysqli->prepare($sql);
$query->bind_param("si", $string_condition, $int_condition);
$query->execute();
$query->store_result();
$query->bind_result($column1, $column2);
$query->fetch();

echo "Column1: {$column1}<br>";
echo "Column2: {$column2}";

Prepared query with PDO:

$sql   = "SELECT column1, column2 FROM table WHERE column3 = ? AND column4 = ?";
$query = $pdo->prepare($sql);
$query->execute([$string_condition, $int_condition]);
$row   = $query->fetchObject();
# $row = $query->fetch(); // Alternative to get indexed and/or associative array

echo "Column1: {$row->column1}<br>";
echo "Column2: {$row->column2}";

Updated code

// Using the NULL coalescing operator here is shorter than a ternary
$id = $_SESSION['u_id'] ?? NULL;

if($id) {
    $sql   = "SELECT email FROM users WHERE u_id = ?";
    $query = $pdo->prepare($sql);    // Prepare the query
    $query->execute([$id]);          // Bind the parameter and execute the query
    $email = $query->fetchColumn();  // Return the value from the database
}

// Putting "$email" on a line by itself does nothing for your code. The only
// thing it does is generate a "Notice" if it hasn't been defined earlier in
// the code. Best use:
//    - The ternary operator: $email = (isset($email)) ? $email : "";
//    - The NULL coalescing operator: $email = $email ?? "";
//    - OR initialize it earlier in code, before the first `if`, like: $email = "";
// N.B. Instead of "" you could use NULL or FALSE as well. Basically in this case 
//    anything that equates to BOOL(FALSE); so we can use them in `if` statements
//    so the following (2 commented lines and 1 uncommented) are effectively
//    interchangeable.
$email = $email ?? "";
# $email = $email ?? FALSE; 
# $email = $email ?? NULL;

// Presumably you will also want to change this function to PDO and prepared statements?
// Although it doesn't actually do anything in the code provided?
$suggestions = selectAll($table);  

// Same as with email, we're just going to use the NULL coalescing operator.
// Note: in this case you had used the third option from above - I've just
//   changed it so there is less bloat.
$optionOne     = $_POST['optionOne'] ?? "";
$optionTwo     = $_POST['optionTwo'] ?? "";
$newSuggestion = $_POST['new-suggestion'] ?? "";

// There's no point nesting `if` statements like this when there doesn't appear to be any
// additional code executed based on the out come of each statement? Just put it into one.
// We now don't need to use empty etc. because an empty, false, or null string all.
// equate to FALSE.
if($newSuggestion && $id && $email && $optionOne && $optionTwo) {
    // Not sure why you've made the the table name a variable UNLESS you have multiple tables
    // with exactly the same columns etc. and need to place in different ones at different
    // times. Which seems unlikely so I've just put the table name inline.
    $sql   = "INSERT INTO suggestions (user_id, email, option_1, option_2) VALUES (?, ?, ?, ?)";
    $query = $pdo->prepare($sql);
    $query->execute([$id, $email, $optionOne, $optionTwo]);
}
else{
    echo "All options must be entered";
}

Without comments

$id = $_SESSION['u_id'] ?? NULL;

if($id) {
    $sql   = "SELECT email FROM users WHERE u_id = ?";
    $query = $pdo->prepare($sql);
    $query->execute([$id]);
    $email = $query->fetchColumn();
}
$email       = $email ?? "";
$suggestions = selectAll($table);  

$optionOne     = $_POST['optionOne'] ?? "";
$optionTwo     = $_POST['optionTwo'] ?? "";
$newSuggestion = $_POST['new-suggestion'] ?? "";

if($newSuggestion && $id && $email && $optionOne && $optionTwo) {
    $sql   = "INSERT INTO suggestions (user_id, email, option_1, option_2) VALUES (?, ?, ?, ?)";
    $query = $pdo->prepare($sql);
    $query->execute([$id, $email, $optionOne, $optionTwo]);
}
else{
    echo "All options must be entered";
}
like image 153
Steven Avatar answered Nov 14 '22 23:11

Steven