0

Possible Duplicate:
How to successfully rewrite old mysql-php code with deprecated mysql_* functions?

I have been posting some question on this site and whenever I could post at least one person could come out and ask me to stop using mysql_ function because it is no more supported which I did not know I was told to use PDO : I have been trying to figure out how it works so that I convert all my codes to it but now the applied it in the code and its seems to be not working though the connecting part does work . here is what I have tried it works with the mysql_ function but not with PDO : any help will be appreciated .

<?php 
#database connection 
$con = new PDO('mysql:host=localhost;dbname=adnan;charset=UTF-8','root','');

$sql = $con->query("SELECT * FROM 
m1debtors INNER JOIN 
m1dtrans 
ON m1debtors.name = m1dtrans.user");

while ($row=$sql->fetchAll(PDO::FETCH_ASSOC)){
    $ name =  $row[' name '];
    $ user = $row[' user ']; 
}

// The JSON standard MIME header.
header('Content-type: application/json');
$array = array('name'=>$name, 'user'=>$user);
echo  json_encode($array);
?>
Community
  • 1
  • 1
Musa
  • 57
  • 1
  • 9

2 Answers2

1

To convert your code into PDO is quite a simple task.
The only thing you actually need is to read examples on the manual page (and to understand them).

As you need only one row in the form of associative array, fetch() can do that already.

$row=$sql->fetch(PDO::FETCH_ASSOC);
// The JSON standard MIME header.
header('Content-type: application/json');
echo  json_encode($row);
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
-3

I would recommend writing a Class which will make using PDO a lot easier.

Then you can do something like this...

$database->query('SELECT id FROM users WHERE name = :name');

$database->bind(':name', 'Jenny');

$row = $database->single();

Take a look at this tutorial for writing your own class.

http://culttt.com/2012/10/01/roll-your-own-pdo-php-class/

philipbrown
  • 554
  • 3
  • 8