MYSQL TO PDO


Joined
Jan 16, 2017
Messages
1
Reaction score
0
Hi guys, Im new to PDO and I cant get hang of it, could anyone please help me convert mysql code to pdo

upload_2017-1-16_12-44-29.png

upload_2017-1-16_12-45-10.png
 
Ad

Advertisements

Joined
Jul 23, 2017
Messages
1
Reaction score
0
First you must to connect your database
If you want use a function you can use this
<?php

define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','');
define('DBNAME','example');

function db_connect
{
try{

$db = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

}
catch(PDOException $e){
echo '<div class="alert alert-danger">'.$e->getMessage().'</div>';
exit;
}
return ($db);​
}
?>

And then to use that's code you can add this

<?php
$db = db_connect();
?>

If you want to connect with your class you can add this
<?php

define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','');
define('DBNAME','example');

class dbconn {
public $db;
public function __construct()
{

}
public function initDBO()
{
try {
$this->db = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS,array(PDO::ATTR_PERSISTENT => true));
$this->db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo '<div class="alert alert-danger">'.$e->getMessage().'</div>';
}
}
}
?>

And then if you want use this you can add this on other class
<?php
class sql extends dbconn {
public function __construct()
{
$this->initDBO();
}
}
?>

If you dont want to use both of them you can just connect like this
<?php

define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','');
define('DBNAME','example');

try{

$db = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

}
catch(PDOException $e){
echo '<div class="alert alert-danger">'.$e->getMessage().'</div>';
exit;
}
?>

After that now you can use that $db like this
<?php
include('connect.php');

$stmt = ' SELECT * FROM item WHERE type LIKE '.$type.' ';
$result = $db->query($stmt);

if($result)
{
if($result->rowCount() === 0){
echo 'Nothing';
else{
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$name = $row['name'];
$type = $row['type'];
$price = $row['price'];
$country = $row['country'];
$image = $row['image'];
$review = $row['review'];​
}​
}​
}
?>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top