Jump to content

[SOLVED] PHP code to select certain records and display only certain fields


jlgray48

Recommended Posts

This program is suppose to select all records from table yahoo with id = 44 and display the field "name" only.

 

Any help is greatly appreciated.

 

 

<?php

 

$conn=mysql_connect("127.0.0.1", "odbc", "") ;

mysql_select_db("uah",$conn);

$sql = "Select name from yahoo where  id=44";

mysql_query($sql,$conn) ;

$result = mysql_query($sql,$conn);

while ($array = mysql_fetch_array($result)) {

  print "$array['name']";

};

 

?>

 

1st: What output does you code provide to you?

2nd(and nowhere near as important):

When you type out SQL syntax (in your code or not) you should allways capitalise the SQL keywords so that it is easyer to read so this:

$sql = "Select name from yahoo where  id=44";

would look like this:

$sql = "SELECT name FROM yahoo WHERE id=44"

Ok what is going on. Are you getting an error or what?

 

Try this:

<?php
$conn=mysql_connect("127.0.0.1", "odbc", "") ; 
mysql_select_db("uah",$conn); 

$sql = "Select name from yahoo where  id=44";

$result = mysql_query($sql,$conn) or die("Error".mysql_error()); 

while ($array = mysql_fetch_array($result)) {
  print "$array['name']";
}
?>

At the very least, always check your queries succeed before trying to use any results.

 

<?php

  $conn = mysql_connect("127.0.0.1", "odbc", "") ;
  mysql_select_db("uah",$conn);
  $sql = "SELECT name FROM yahoo WHERE  id = 44";
  if ($result = mysql_query($sql,$conn)) {
    if (mysql_num_rows($result)) {
      while ($row = mysql_fetch_array($result)) {
        print $row['name'];
      }
    } else {
      echo "No results found";
    }
  } else {
    echo "Query failed<br />$sql<br />" . mysql_error();
  }

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.