7

I was using mysqli_fetch_array and the counting was right until I changed to fetch(), which now only returns the total number of rows instead of returning each number for each row.

So for row one, I want to echo "1", and so on.

NEW NOTE :Everything else inside the while statement is returning correct values, except the counter which returns the total number of rows whereas I want a row number in the order that it was selected from the sql statement.

As requested. This is my connection.

I don't know if i'm suppose to be checking " $e->getMessage();" on every query since I'm using this connection for all my queries.

try {
    $dbh = new PDO('mysql:host=localhost;dbname=my_db;charset=utf8', 'usr', 'pwd',
                    array(PDO::ATTR_EMULATE_PREPARES => false, 
                          PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
                  );
} catch (PDOException $e){
    echo $e->getMessage();
}

This worked

$query = mysqli_query($con, 'SELECT * FROM music');

$count = 0;
while($row = mysqli_fetch_array($query)){
    $count++; 
    echo $count;
}

The new doesn't work.

$query = $dbh->query('SELECT * FROM music');

$count = 0;
while($row = $query->fetch()){
    $count++; 
    echo $count;
}
5
  • are you still using mysqli or now PDO? Commented Aug 8, 2014 at 8:33
  • @iswinky, Yes i'm using pdo Commented Aug 8, 2014 at 8:38
  • have you looked into this: php.net/manual/en/pdostatement.rowcount.php ?? Commented Aug 13, 2014 at 22:54
  • PDOStatement::rowCount — Returns the number of rows affected by the last SQL statement Commented Aug 14, 2014 at 12:56
  • 1
    PDO have a little different behavior. This is a replacement for your mysqli (stackoverflow.com/questions/25199122/…). Commented Aug 18, 2014 at 18:32

5 Answers 5

2

Works fine, use a try catch do see if your PDO connection is working.

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

$sql = 'SELECT * FROM music';
$sth = $dbh->query($sql);

$count = 0;
while($row = $sth->fetch()){
    $count++; 
    echo $count;
}

I've just tested this and it works fine. Either your PDO connection is incorrect or your query returns no results. I suggest you var_dump($dbh) and see if it returns a PDO object or check that your query is correct. Is your table called music? It is case sensitive.

You also need to change your connection form mysqli to PDO

$mysqli = new mysqli("localhost", "user", "password", "database");

to

$dbh = new PDO('mysql:host=localhost;dbname=database', 'user', 'password');

You can also throw PDO exceptions to see if any are occuring: PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION

Sign up to request clarification or add additional context in comments.

13 Comments

Can u please explain what's making what i've done not to work and why this will work?
You haven't called execute() on the the $query object
Why are you using prepare, this statement doesn't have to be prepared? I'm not using any external values in my question
My bad. Your code looks correct, have you checked your PDO object?
Try using a try catch block and change your mysqli connection to PDO if you haven't already
|
0

$conn->exec("SET CHARACTER SET utf8");

http://coursesweb.net/php-mysql/pdo-select-query-fetch

Comments

0

What about:

if ($pdo){  
    $query=$pdo->prepare("SELECT count(*) as cnt FROM music");
    if($query->execute()){
        $count = $query->fetch()[0];//or fetch()['cnt'] 
        echo $count;
    }
}

Comments

0

PDO have a little different behavior. This is a replacement for your mysqli.

try {
    $dbh = new PDO('mysql:host=localhost;dbname=database', 'user', 'password',array(
        PDO::ATTR_EMULATE_PREPARES => false, 
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        // optional
        PDO::MYSQL_ATTR_INIT_COMMAND    => 'SET NAMES utf8',
    ));

    $count = 0;
    foreach ($dbh->query("SELECT * FROM `music`") as $row) {
        $count++; 
        echo $count;
    }
}  catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    exit();
}

I hope that helped.

Comments

-1

Try using PDO::FETCH_NUM to get the row count directly :-

$countquery = $dbh->query('SELECT COUNT(1) FROM music');
$rowCount = 0;
$rowCount = $countquery ->fetch(PDO::FETCH_NUM);
echo $rowCount;
//And then do another query for the real data if need be

* This makes use of a query to get the row count, and saves you the time taken by the while loop.

2 Comments

...and instead sends out same query to server twice, effectively doubling servers work load. I wouldn't prefer this way unless I know for certain that the data I'm querying is very small and creating the result set will be trivial for server.
@TuncayGöncüoğlu SELECT COUNT(1) ... is a very light query, it is usually the recomended option in mysql of getting the size of the result set before doing a heavier query, especially when using innodb. Besides, iterating over all rows scales (very) badly as the number of rows increases.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.