0

I am trying to get a single value from the database. Somehow it does not echo out. I know about the security deprecation and will use PDO later on this is just as test. I filled in the correct table. When I use the sql I have in phpmyadmin it correctly gives me the value i want.

  <?php
    include 'connectdb.php';

    $result = mysql_query("SELECT id FROM table ORDER BY id DESC LIMIT 1");

    $row = mysql_fetch_row($result);


    echo $row["id"];

    mysql_close();

   ?>
DaViDa
  • 641
  • 1
  • 8
  • 28
  • it's a better practice to add `mysql_error()` to check if there's any error. So try this, `$result = mysql_query("SELECT id FROM table ORDER BY id DESC LIMIT 1") or die("Error :: " . mysql_error());` to check if any error is reported – Fallen Jul 26 '14 at 18:38
  • 3
    `echo $row[0];` as [`mysql_fetch_row — Get a result row as an enumerated array`](http://php.net/manual/en/function.mysql-fetch-row.php) – Sean Jul 26 '14 at 18:38
  • 1
    I trust that your table isn't really called 'table'!?!?!? – Strawberry Jul 26 '14 at 18:39
  • 1
    @Sean make your comment an answer and itll get accepted and upvoted... for more rep :) – John Ruddell Jul 26 '14 at 18:40
  • I don't really understand the point of fetch_row. Why not always use fetch_array? The overhead must be trivial. – Strawberry Jul 26 '14 at 18:45

3 Answers3

2

per the docs ->mysql_fetch_row — Get a result row as an enumerated array http://php.net/manual/en/function.mysql-fetch-row.php so you want

echo $row[0];

--
note: also from the docs -> Warning [mysql_ functions/] extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information.

Sean
  • 12,443
  • 3
  • 29
  • 47
1

You may try to use this:

echo $row[0];

instead of

echo $row["id"];
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1

This is how you would do this in mysqli (as you point out, you should not be using mysql_ functions)

You can put $con elsewhere and use include each time you use a query. (Replace the values in the connection string with what they actually are, in your case.)

<?php

$con = mysqli_connect('localhost',$mysql_user,$mysql_password,$mysql_dbname); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } mysqli_select_db($con,"xyz");

$result = mysqli_query("select id from table order by id desc limit 1");

$result_row = mysqli_fetch_array($result);

echo $result_row['id'];

?>
Brian DeMilia
  • 13,103
  • 1
  • 23
  • 33