php get data from prepared select code example

Example 1: php prepared statement select

// Multiple rows:
$sql = "SELECT * FROM users WHERE id=?";
$stmt = $conn->prepare($sql); 
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    echo $row['name'];
}

//Single row:
$sql = "SELECT user FROM users WHERE id=?"; // SQL with parameters
$stmt = $conn->prepare($sql); 
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
$user = $result->fetch_assoc(); // fetch data  

// Update/delete from
$sql = "UPDATE users SET rank=?, status=? WHERE id=?"; // SQL with parameters
$sql = "DELETE FROM users WHERE id=?";
$stmt = $conn->prepare($sql);

$stmt->bind_param('sss', $rank, $status, $id);
$stmt->execute();

Example 2: php get data from prepared select

//on sql server
public function get_data_from($id){
  $request = "SELECT * FROM tableName WHERE id = ?";

  //preparing the request
  $stmt = $this->dbh->prepare($request);

  //executing the request
  $stmt->execute( array($id)  );

  //fetching the result of the request
  $result = $stmt->fetchAll();

  return $result;
}

Tags:

Php Example