Jump to content


Photo

how do i extract value from sql query


  • Please log in to reply
1 reply to this topic

#1 essjay_d12

essjay_d12
  • Members
  • PipPipPip
  • Advanced Member
  • 121 posts

Posted 27 March 2006 - 08:14 PM

i need to pull out the value 'FAVOURITES'

$sql = "SELECT FAVOURITES FROM users WHERE USERNAME = '$username'";

how do i do this using php?

thanks

d

#2 toplay

toplay
  • Staff Alumni
  • Advanced Member
  • 973 posts

Posted 27 March 2006 - 08:56 PM

Checkout various tutorials. Below is an example obtained from our FAQ pinned topic at the top of the newbie topic area.

I'm assuming that FAVOURITES is a column name and not a value you want to retrieve by specifying it in the "where" clause.

$username = 'something';  // set it first

// Connect to MySQL server first – You can use variables instead of these literals
$db = mysql_connect('localhost', 'username', 'password');
if (!$db) {
   echo 'Could not connect to MySQL server. <br />Error # ', mysql_errno(), ' Error msg: ', mysql_error();
   exit;
}

// Select the database you want to use – You can use a variable here too instead
if (!mysql_select_db('DBname', $db)) {   // Did selection fail?
   // Handle error
   echo 'DB Selection failed. <br />Error # ', mysql_errno(), ' Error msg: ', mysql_error();
   exit;
}

// An example for retrieving zero or more rows
$sql = "SELECT FAVOURITES FROM `users` WHERE `USERNAME` = '$username'";
$result = mysql_query($sql, $db);
if (!$result) {
   // Handle error
   echo 'Query failed. SQL: ', $sql, '<br />Error # ', mysql_errno(), ' Error msg: ', mysql_error();
   exit;
}
// The while loop stops when there's no data left; it might not even go in loop
// and echo anything when there's no data returned on the first call to
// mysql_fetch_assoc()
while($row = mysql_fetch_assoc($result)) {  // Retrieve data until no more
   echo $row['FAVOURITES'], '<br />';
}

// Optional – Free up memory. Done automatically when script ends
if (!mysql_free_result($result)) {  
   // Handle error or ignore it
   echo 'Freeing results failed. <br />Error # ', mysql_errno(), ' Error msg: ', mysql_error();
   exit;
}


// Optional – Close MySQL connection. Will be closed at end of script anyway
// Do NOT put a mysql_close() after a query and before fetching data!
if (!mysql_close($db)) {  
   echo "Couldn't close database <br />";  // or ignore error
   exit;
}






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users