Jump to content

how do i extract value from sql query


essjay_d12

Recommended Posts

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.

[code]
$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;
}

[/code]

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.