I have a function that allows me to perform sql queries depending on what type of SQL server the user has chosen. The function works fine getting a single row of data, but it never returns more than 1 row.
This is the sql function:
function sqlQuery($query){
switch (DATABASE_TYPE) {
case 'MYSQL':
// Establishes a connection to the database.
$connection = mysql_connect(DATABASE_LOCATION, DATABASE_USERNAME, DATABASE_PASSWORD);
if(!$connection){
throw new Exception(mysql_error(), 1);
}
mysql_select_db(DATABASE_NAME);
// Performs the query.
global $response;
$response = mysql_query($query);
if(!$response){
throw new Exception(mysql_error(), 1);
}
return mysql_fetch_array($response);
break;
}
}
And like I said above, this works just fine for single row queries, but I can't get any more.
If I try this:
$sql = "SELECT * FROM test"
$rows = sqlQuery($sql);
foreach($rows as $value){
echo($value);
}
If row 1 of test is 1 | Hello | PHP
it would echo 11HelloHelloPHPPHP
it is simple to do it
$sql = "SELECT * FROM test";
$data = array();
while($rows = mysql_fetch_assoc($sql))
{
$data[] = $rows ;
}
return $data;
To shed a little more light on raheel's answer, mysql_fetch_array only returns a single row of results. Using a while loop allows you to continue to grab additional rows as long as they exist. For additional information, you may want to look at Getting dynamic array from inside a function
If you have more number of rows you have to use forloop to get all the rows.. that is it will return as resourceid #-- please print_r or echo your result and check it.. after that use that result inside mysql_fetch_row ~ mysql_fetch_array ~ antything else you want.. and store it in array with its id as key... please check the following edited code,
function sqlQuery($query){
switch (DATABASE_TYPE) {
case 'MYSQL':
// Establishes a connection to the database.
$connection = mysql_connect(DATABASE_LOCATION, DATABASE_USERNAME, DATABASE_PASSWORD);
if(!$connection){
throw new Exception(mysql_error(), 1);
}
mysql_select_db(DATABASE_NAME);
// Performs the query.
global $response;
$response = mysql_query($query);
if(!$response){
throw new Exception(mysql_error(), 1);
}
while($rows = mysql_fetch_array($sql))
{
$data[$rows['id]] = $rows;
}
return $data;
break;
}
}
I was able to fix the issue by changing what type of data is returning from:
return mysql_fetch_array($response);
to:
$rows = array();
while($row = mysql_fetch_array($response)){
array_push($rows, $row);
}
return $rows;
Thanks for all your help!