I created a function that read data from a mysql db.
I want to put the data into a array and read that outside of the PHP function.
function showCategory($con) {
$sql = "SELECT * FROM kategorien";
$kategorien = array();
$result = $con->query($sql);
while($row = $result->fetch_assoc()) {
$kategorien[] = $row["kategorie"];
return $kategorien;
}
}
To load the data outside from function:
$kategorien = showCategory($con);
echo $kategorien['kategorie'][0];
It doesn't work. Whats wrong?
The
return $kategorien;
will exit the loop and the function, so move this to the end of the function and not in the loop.
function showCategory($con) {
$sql = "SELECT kategorie FROM kategorien";
$kategorien = array();
$result = $con->query($sql);
while($row = $result->fetch_assoc()) {
$kategorien[] = $row["kategorie"];
}
return $kategorien;
}
Rather than using *, it's also worth specifying the column names if you only need some of them.
Display the data using...
$kategorien = showCategory($con);
print_r( $kategorien );
or use a foreach()...
$kategorien = showCategory($con);
foreach ( $kategorien as $kat ) {
echo $kat.PHP_EOL;
}
Use this instead, because returning $kategorien will exit the loop, so it will only run once.
function showCategory($con) {
$sql = "SELECT * FROM kategorien";
$kategorien = array();
$result = $con->query($sql);
while($row = $result->fetch_assoc()) {
$kategorien[] = $row["kategorie"];
}
return $kategorien;
}
Related
I'm trying to get the result of a stored procedure in MySQL into an array with use of php. The code I have:
function get_all_uzovi($dbc) {
//$query = "SELECT diagnose_id, diagnose_code, specialisme_agb_code_fk
// FROM tbl_diagnoses
// WHERE specialisme_agb_code_fk = '$var_chosen_specialism'
// ORDER BY diagnose_code ASC";
$result = mysqli_query($dbc,"CALL spGetUzovi");
//WHAT DOES NOT WORK:
//$data = array();
//while ( $row = $result->fetch_assoc() ) {
// $data[] = $row;
//}
//return json_encode($data);
//WHAT DOES WORK:
while ($row = mysqli_fetch_array($result)){
echo $row[0] . " - " . + $row[1];
}
}
The code under "//WHAT DOES NOT WORK" is what I need: the result as a json format. For some reason it gives me nothing..
The code under "//WHAT DOES WORK", does work, but this is not what I want.
the code for the sp:
CREATE DEFINER=`ziekenh3`#`localhost` PROCEDURE `spGetUzovi`()
NO SQL
SELECT *
FROM tbl_uzovi
the code that I use when working with queries (which does work) instead of sp:
function get_diagnoses($dbc,$var_chosen_specialism) {
$query = "SELECT diagnose_id, diagnose_code, specialisme_agb_code_fk
FROM tbl_diagnoses
WHERE specialisme_agb_code_fk = '$var_chosen_specialism'
ORDER BY diagnose_code ASC";
$result = mysqli_query($dbc,$query);
$data = array();
//while ( $row = $result->fetch_assoc() ) {
while ( $row = mysqli_fetch_assoc($result) ) {
$data[] = $row;
}
return json_encode($data);
}
Any thoughts?
Does this work?
function get_all_uzovi($dbc) {
$result = mysqli_query($dbc,"CALL spGetUzovi");
$data = array();
while ( $row = $result->fetch_assoc() ) {
$data[] = $row;
}
return json_encode($data);
}
I Solved it. A bit of a stupid problem: there where some fields in the result set that contained characters like: , ( . etc. I don't think json likes this..
When I did a SELECT * FROM on another table it worked. So, my code that works now is:
function get_all_uzovi($dbc) {
$q = "CALL spGetUzovi";
$r = mysqli_query($dbc,$q);
while ($row = mysqli_fetch_assoc($r)) {
$data[] = $row;
}
return json_encode($data);
}
I'm sorry for the inconvenience!
I try to query a SQL database and save data into a custom array, but the array always repeats last row*num rows on database.
php:
class Cst
{
public $ParagemID;
public $Designacao;
public $DecimalDeGrauY;
public $DecimalDeGrauX;
}
require 'config.php';
$dsn = array( "Database"=>"$database", "UID"=>"$username", "PWD"=>"$password", "LoginTimeout"=> 60);
$db = sqlsrv_connect($server, $dsn);
$sql = "SELECT ParagemID, Designacao, DecimalDeGrauY, DecimalDeGrauX FROM adoParagens WHERE ParagemID >= 20000";
$stmt = sqlsrv_query($db, $sql);
$locations = new Cst();
$location=array();
$i=0;
while( $row = sqlsrv_fetch_object($stmt))
{
$locations->ParagemID = $row->ParagemID;
$locations->Designacao = $row->Designacao;
$locations->DecimalDeGrauY = $row->DecimalDeGrauY;
$locations->DecimalDeGrauX = $row->DecimalDeGrauX;
//echo json_encode($locations);
$location[$i]= $locations;
$i++;
}
echo json_encode($location);
It looks like you're always working with same instance of that object. Updating it for each row will also update all copies of it, as they are in fact the same object.
Try this instead.
...
$location = array();
while( $row = sqlsrv_fetch_object($stmt) )
{
$data = array();
$data['ParagemID'] = $row->ParagemID;
$data['Designacao'] = $row->Designacao;
$data['DecimalDeGrauY'] = $row->DecimalDeGrauY;
$data['DecimalDeGrauX'] = $row->DecimalDeGrauX;
$location[]= $data;
}
...
try using a 2 dimensional array.
$i=0;
while( $row = sqlsrv_fetch_object($stmt))
{
$location[$i][$locations->ParagemID/*put your val*/] = $row->ParagemID;
$location[$i][$locations->Designacao/*put your val*/] = $row->Designacao;
$location[$i][$locations->DecimalDeGrauY/*put your val*/] = $row->DecimalDeGrauY;
$location[$i][$locations->DecimalDeGrauX/*put your val*/] = $row->DecimalDeGrauX;
//echo json_encode($locations);
$i++;
}
Please tell, why this code is wrong?
function myres () {
$db = new mysqli("localhost","userrr","pass","mvc");
$res = $db->query("SELECT * FROM news ");
return $res;
}
while ($row = myres()->fetch_row()) {
echo $row[0];
}
P.S.
this code is working:
$db = new mysqli("localhost","userrr","pass","mvc");
$res = $db->query("SELECT * FROM news ");
while ($row = $res->fetch_row()) {
echo $row[0];
}
Here you call myres() every time, I think:
while ($row = myres()->fetch_row()) {
echo $row[0];
}
So every time $row contain first row of the result, and it will not stop. It will works fine, I think:
$res = myres();
while ($row = $res->fetch_row()) {
echo $row[0];
}
I get an array of values returned from the following function:
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
I now want to use these values in a new function, where each "user_id" is used to collect text from the database through this function:
function get_text($writer) {
$writer = mysql_real_escape_string ($writer);
$sql = "SELECT * FROM `text` WHERE user_id='$writer' ORDER BY timestamp desc";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
However the returned value from the first function is an array, and as I've learnt the hard way, arrays cannot be treated by "mysql_real_escape_string".
How can I make the second function handle the values that I got from the first function?
Any responses appreciated.
Thank you in advance.
Your first mistake is to use mysql_fetch_assoc when only selecting one column. You should use mysql_fetch_row for this. This is likely going to fix your primary problem.
Could look like this:
$subs = get_subscribitions($whateverId);
$texts = get_text($subs);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_row($result)) {
$user_id = $row['user_id'];
$rows[$user_id] = $user_id;
}
mysql_free_result($result);
return $rows;
}
function get_text($writer) {
$writers = implode(",", $writer);
$sql = "SELECT * FROM `text` WHERE user_id IN ({$writers}) ORDER BY timestamp DESC";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_array($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
}
This will save you a lot of time, because you can get all data from 'text' in one statement.
The solution is to avoid placing arrays in your $rows array in the first function. Instead of:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
try:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
This will place only the value from column 'user_id' in the $rows array.
In order to use the second function you must iterate over the array returned from the first one. Something like this could work for you:
$user_subscriptions = get_subscribitions($user);
foreach($user_subscriptions as $subscription) {
$texts = get_text($subscription['user_id']);
foreach($texts as $text) {
// do something with the fetched text
}
}
As George Cummins says,
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
and, to speed up the second function:
function get_text($writer)
{
$sql = "SELECT * FROM `text` WHERE user_id in (".implode(',',$writer).") ORDER BY timestamp desc";
$rows = array();
if ($result = mysql_query($sql))
{
while ($row = mysql_fetch_assoc($result))
{
$rows[] = $row;
}
mysql_free_result($result);
}
return $rows;
}
The change to the query means that you only do one in total rather than one for each ID thus removing the time taken to send the query to the server and get a response multiple times. Also, if the query fails, the function returns an empty array
Use :
string implode ( string $glue , array $pieces )
// example, elements separated by a comma :
$arrayasstring = impode(",", $myarray);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$row = mysql_fetch_row($results);
mysql_free_result($result);
return intval($row['user_id']);
}
it return only the user id you can used it in the 2nd function
$qVraagGroepenOp = "SELECT * FROM $tabele WHERE $where";
$rVraagGroepenOp = mysql_query ( $qVraagGroepenOp );
$aVraagGroepenOp = mysql_fetch_assoc ( $rVraagGroepenOp )
and I converted that to a function
vraagOp("testtable","testtable_ID = $id");
function vraagOp($table,$where)
{
$qVraagOp = "SELECT * FROM $table WHERE $where";
$rVraagOp = mysql_query( $qVraagOp );
$aVraagOp = mysql_fetch_assoc( $rVraagOp );
return $aVraagOp;
}
only the problem is when i need more then one row i need to use a while loop
$qVraagGroepenOp = "SELECT * FROM testtable where testtype = test";
$rVraagGroepenOp = mysql_query ( $qVraagGroepenOp );
while ( $aVraagGroepenOp = mysql_fetch_assoc ( $rVraagGroepenOp ) )
{
echo "testing <br>";
}
It wont work anymore is there a trick to make my function work with this while loop?
This won't work but I want to reach to something like it
while (vraagOp("testtable","testtype = test"))
{
echo "testing <br>";
}
Is this possible?
This could be done with static variables in the function scope.
function vraagOp($table,$where)
{
static $rVraagOp;
if(!$rVraagOp){
$qVraagOp = "SELECT * FROM $table WHERE $where";
$rVraagOp = mysql_query( $qVraagOp );
}
return mysql_fetch_assoc( $rVraagOp );
}
That should do what you're after.
This function returns an array of rows - it's a generic pattern yu can use almost anywhere you get multiple rows from a query.
function vraagOp($table,$where)
{
$sql= "SELECT * FROM $table WHERE $where";
$query= mysql_query($sql);
if ($query != false)
{
$result = array();
while ( $row = mysql_fetch_assoc($query) )
$result[] = $row;
return $result;
}
return $false;
}
//usage
$rows = vraagOp($table,$where);
if ($rows)
{
foreach ($rows as $row)
use($row);
}
This function will 'cache' the mysql result resource from each unique $table/$where combination, and fetch the next result from it on each subsequent call. It will return an associative array for each row, or false when there are no rows left.
function vraagOp($table, $where)
{
// Holds our mysql resources in a map of "{$table}_{$where}" => resource
static $results = array();
$key = $table . '_' . $where;
if (!isset($results[$key]))
{
// first call of this particular table/where
$results[$key] = mysql_query("SELECT * FROM $table WHERE $where");
}
$row = mysql_fetch_assoc($results[$key]);
if ($row === false)
// remove this key so a subsequent call will start over with a new query
unset($results[$key]);
return $row;
}
// Usage
while ($row = vraagOp("table1", "where field > 7")) {
print_r($row);
}
This
while (vraagOp("testtable","testtype = test"))
{
echo "testing <br>";
}
will work if you change VraagOp() to return false when no matching record was found.
You would have to move the mysql_query() part out of VraagOp(), and just leave the mysql_fetch_assoc part in.
However, I can't really see what benefit there would be? You would just be building a (unnecessary) wrapper around mysql_fetch_assoc(), wouldn't you?
You'll need to turn vraagOp() into an iterator and then use foreach() in order to make this work.
Your example won’t work because the condition is executed on every iteration. That means vraagOp("testtable","testtype = test") would be called with each iteration until it returns a falsely value. mysql_fetch_assoc does that but your function doesn’t.
How can we call function inside while loop example is below :
$sql_gpfsF="SELECT * FROM emp_salary";
$result_gpfsF=mysql_query($sql_gpfsF);
while($row_gpfsF=mysql_fetch_assoc($result_gpfsF))
{
call_function();
}
function call_function()
{
echo " Function Called </ br>";
}