Its Wawan
Its Wawan

Reputation: 599

mysql PDO doesnt work

I've a little problem here..

I am using jquery easy UI to get data from mysql and then write a table in my php application..

nah.. the problem is.. my code or my query doesn't work..

When I am using my old mysql_connect, my code works well... but when I try to write it to mysql, I get nothing...

Here is my old code:

$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
    $rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10;
    $offset = ($page-1)*$rows;

    $result = array();

    $conn = mysql_connect('127.0.0.1','root','');
    mysql_select_db('colosus',$conn);

    $rs = mysql_query("select count(*) from user");
    $row = mysql_fetch_row($rs);
    $result["total"] = $row[0];

    $rs = mysql_query("select * from user limit $offset,$rows");

    $rows = array();
    while($row = mysql_fetch_object($rs)){
        array_push($rows, $row);
    }
    $result["rows"] = $rows;

    echo json_encode($result);

and its the PDO query code...

$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
    $rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10;
    $offset = ($page-1)*$rows;

    $result = array();



    $rs = $db->query("select count(*) from user");
    $row = $rs->fetch(PDO::FETCH_NUM);
    $result["total"] = $row[0];

    $rs = $db->query("select * from user as u, leveluser as l where u.idLevelUser = l.idLevelUser limit $offset,$rows");

    $rows = array();
    while($row = $rs->fetch(PDO::FETCH_OBJ)){
        array_push($rows, $row);
    }
    $result["rows"] = $rows;

    echo json_encode($result);

The last query (PDO) doesn't work.. I dont know why.. anybody can help me???

Upvotes: 3

Views: 2900

Answers (2)

NullPoiиteя
NullPoiиteя

Reputation: 57322

create the pdo connection like

$db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8',
               'username',
               'password', 
               array(PDO::ATTR_EMULATE_PREPARES => false,
                     PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
               );

try query like

$query= $db->prepare("select * from user as u,
                       leveluser as l
                       where u.idLevelUser = l.idLevelUser
                       limit $offset,$rows");

$query->execute();
$result=$articlequery->fetch(pdo::FETCH_ASSOC);

Upvotes: 0

Alain
Alain

Reputation: 36954

Looks like you forget to instanciate your $db object.

Try to put this before $result = array();

$db = new PDO("mysql:host=127.0.0.1;dbname=colosus", 'root', '');

Upvotes: 2

Related Questions