PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
Hello. I'm developing a one size fits all mysql function to write one line instead of 4 when I eed to putt something from a database. I want this function to execute the query that is passed to it, and return the result in the fom of an associative array. However, I ran into a problem when I'm expecting more than one row to be returned. Here is my code:
function sql_pull ($query) {
//performs a query on a database, and returns the results
$result = mysql_query($query, $db);
if (mysql_num_rows($result)==1){
$row = mysql_fetch_assoc($result);
return $row; } //returns the one row it found
else if (mysql_num_rows($result)==0) {
return NULL; } //return a null value meaning no results returned
else {
//what do I do here? There is more than one result...
}
}
sql_pull("SELECT * FROM table WHERE blah=blah");
//pretty slick, huh?
Thanks for the help!
Last edited by evilmonkey on Sun Jul 18, 2004 12:04 pm, edited 1 time in total.
function sql_pull ($query) {
//performs a query on a database, and returns the results in a loop
$result = mysql_query($query, $db);
if (mysql_num_rows($result)==1){
$row = mysql_fetch_assoc($result);
return $row; } //returns the one row it found
else if (mysql_num_rows($result)==0) {
return NULL; } //return a null value meaning no results returned
else {
while (true)
{
$row = mysql_fetch_assoc($result);
if ($row == false) break;
echo $row['name'];
}
}
}
sql_pull("SELECT * FROM table WHERE blah=blah");
//pretty slick, huh?
function select(){
$result = mysql_query($query); #runs the query
$data = array();
if(mysql_num_rows($result)>1){ #checks to see if there is more than 1 row returned
for($x=0;$x<mysql_num_rows($result);$x++){
$data[] = mysql_fetch_assoc($result);
}
}else{
$data = mysql_fetch_assoc($result); #places single result into array
}
return $data;
}
It returns all the results as an array. If theres only 1 result then the format is $array['fieldname'] and if there is a number or rows you use $array[0]['fieldname'], $array[1]['fieldname']; etc.