How can i display result of a single cell query?
my query is

$author=$_POST["authorname"];
$q="Select authorid from authors where AuthorName=$author";
$resultauthor=mysql_query($q,$connect);
$num=mysql_num_fields($resultauthor); [B]<<Error coming here![/B] :( mysql_num_fields(): supplied argument is not a valid MySQL result resource in

Dani AI

Generated

Good catch by — the error happens because the SQL failed, so mysql_query() returned FALSE and mysql_num_fields() was handed a boolean instead of a result resource. Always check the query result before calling result functions; printing the final SQL string makes syntax/quoting errors obvious. (php.net)

Quick troubleshooting checklist:

  • Confirm the POST value is present and non-empty.
  • Print or log the exact SQL you’re sending and run it in the DB client.
  • Verify the DB connection is valid.
  • If the query fails, inspect the DB error text (don’t ignore it). Using the native error helper will show the real reason. (php.net)

How to get a single cell safely and clearly:

  • Recommended (modern): use PDO with a prepared statement and fetch a single column.
    // using PDO (recommended)
    $stmt = $pdo->prepare('SELECT authorid FROM authors WHERE AuthorName = :name LIMIT 1');
    $stmt->execute([':name' => $authorName]);
    $authorId = $stmt->fetchColumn(); // single value or false if none
    if ($authorId !== false) {
      echo $authorId;
    } else {
      echo 'No author found';
    }
  • Quick legacy approach (if you must keep old code): check the query return for FALSE, then fetch the row or use the single-cell helper — but plan to migrate away from ext/mysql. (php.net)

Security and future-proofing: do not build SQL by concatenating untrusted input; use parameterized queries (prepared statements) to avoid SQL injection. The original mysql_* extension is deprecated/removed in modern PHP — migrate to PDO or MySQLi when possible. (owasp.org)

(Note: confirmed the fix worked; the above expands common pitfalls and shows a safer, more maintainable way to fetch a single value.)

Recommended Answers

All 2 Replies

The error is here

mysql_query($q,$connect);

Try chaging the query to this

$q="Select authorid from authors where AuthorName='$author'";

Probably its because of the missing '' or simply, you´re not getting the POST variable authorname

Try this

$author=$_POST["authorname"];
echo $author;

Do you get what you expect?
If nothing of this works, then you have a problem in $connect

Cheers

thnx. I just figured it out! thnx again

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.