how to use sql with pdo – PHP

 

 

connect db

try {
$user = "root";
$pass = "pass";
$dbh = new PDO('mysql:host=localhost;dbname=db', $user, $pass);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
};

SELECT

$stmt = $dbh->prepare(" SELECT count(*) FROM `tb` WHERE name = :i ");

$stmt->execute(array("i"=>"$v"));
//値存在してる?
$number_of_rows = $stmt->fetchColumn(); 

if ($number_of_rows == 0) {
echo "値存在してない";
}else{
echo "値存在してる";
};

SELECT2

$q = $dbh->prepare("SELECT * tb WHERE name = :i");
$q->bindValue(':i', 'something');
$q->execute();

if ($q->rowCount() > 0){
    $check = $q->fetch(PDO::FETCH_ASSOC);
    $row_id = $check['id'];
    echo $row_id;
    // do something
}

//or

$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname LIMIT 1");
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname',  'Bloggs');
$q->execute();

if ($q->rowCount() > 0){
    $check = $q->fetch(PDO::FETCH_ASSOC);
    $row_id = $check['id'];
    // do something
}

UPDATA

$sql = 'update tb set set_column =:set_name where where_column = :where_value';
$stmt = $dbh -> prepare($sql);
$stmt->bindParam(':set_name', $update_set_name, PDO::PARAM_STR);
$stmt->bindParam(':where_value', $update_where_value, PDO::PARAM_STR);
$stmt->execute();

INSERT

$stmt = $dbh -> prepare("INSERT INTO tb (column_one, column_tow) 
	                     VALUES(:value_one, :value_tow)");
$stmt->bindParam(':value_one', $value_one, PDO::PARAM_STR);
$stmt->bindParam(':value_tow', $value_tow, PDO::PARAM_STR);
$stmt->execute();

DELETE

try {
    $sql = 'DELETE FROM tb WHERE id LIKE ?';
    $stmt = $dbh->prepare($sql);
    $stmt->execute(  array('va%')  );
    $rows=$stmt->fetchAll(PDO::FETCH_ASSOC);

	} catch(PDOException $e) {
		echo $e->getMessage();
		die();
	}