PHP 1-liner each() with mysql_fetch_assoc() - php

Trying to create a 1-liner to loop through a mysql result set.
Example:
$sql = "SELECT uid, role FROM usr WHERE uid = '$this->uid'";
$r = db::q($sql);
if($r->rows()) {
$q = mysql_fetch_assoc($r->result);
while(list($k, $v) = each($q)) { // would like to omit line above and consolidate here
$_SESSION['usr'][$k] = $this->$k = $v;
}
}
problem is that consolidating while loop like so:
while(list($k, $v) = each(mysql_fetch_assoc($r->result))
returns an error a la each() not getting object or array, even though of course it is. I think the problem is a casting issue, but it does not seem you can do:
each( (array) mysql_fetch_assoc($r->result))
Any ideas? I like to code as tersely as possible, and having "$q = mysql_fetch_assoc($r->result)" everywhere will annoy me, does already.
Keep posted...
Thanks!

Do yourself a favor and use PDO:
$query->fetchAll();
MySQLi also has a similar method / function.

You could make the mysql_fetch_assoc call part of your while condition:
while (($q = mysql_fetch_assoc($r->result)) && list($k, $v) = each($q)) {
$_SESSION['usr'][$k] = $this->$k = $v;
}

$_SESSION['usr'] = mysql_fetch_assoc($r->result);
or ( if $_SESSION['usr'] already contains some elements with other keys you want to keep)
$_SESSION['usr'] = array_merge($_SESSION['usr'], mysql_fetch_assoc($r->result));

Related

Codeigniter function array always returns no

Rather noobish question. Given the following code:
public function in_group($group)
{
$session = $this->CI->session->userdata('logged_in');
$query = $this->CI->db->get_where('people_groups', array('people_id' => $session['user_id']));
$array = array();
foreach ($query->result() as $row)
{
$array = $row->group_id;
}
if ( $array == $group)
{
return 'YES';
}
return 'no';
}
The result is always no, when in fact it should be yes according to the database.
What i am trying to do is to check the people_groups table to see if the current user is in the requested $group. I have research as to how to use the arrays in the following way, but i fear i have done something rather noobish.
NOTE: The $group_id references the column in the table that stores the group id's
It's not inserting values into the array, so change this:
$array = $row->group_id;
to
$array[] = $row->group_id;
You should just change your query to select where there is a row with that user and group id, something like this:
$this->CI->db->select('*');
$this->CI->db->from('people_groups');
$this->CI->db->where('people_id', $session['user_id']);
$this->CI->db->where('group_id', $group);
$query = $this->CI->db->get();
Then you can just check if there is a result or not, instead of looping through all the results.
I descovered that i missed a section in the user guide to achieve what i wanted the correct code should have been:
public function in_group($group)
{
$session = $this->CI->session->userdata('logged_in');
$query = $this->CI->db->get_where('people_groups', array('people_id' => $session['user_id']));
foreach ($query->result_array() as $row)
{
if ( $row['group_id'] == $group)
{
return 'YES';
}
return 'no';
}
}
Thank you to the people who responded, I hope this helps other people making silly mistakes :)

Get ID for each array element inside second array

I need to get unique ID for each array element inside second array. That ID already exist in table but I cant get them separately. URL that am getting now looks like this: http://page.com/index.php?p=view&m=area&id=173id=552id=768id=36id=217id=
I need just one ID and if first is used set second and so on.
I know that I should use mysqli or PDO and normalized tables but that later, now I need help with this.
This is the code:
$res= mysql_query("SELECT * FROM area WHERE user='$user' ORDER BY date") or die("Error: " . mysql_error());
while($row = mysql_fetch_assoc($res))
{
$id = $row['id'];
$x = array();
$parent = array();
foreach($row as $value)
{
if ($value == $id) continue;
else if ($value == $user) continue;
$result = explode(",", $value);
foreach($result as $newvalue)
{
$query = "SELECT x,firm FROM list where list.x='$newvalue'";
$result = mysql_query($query);
$r = mysql_fetch_assoc($result);
$x[] = $r['x'];
$xx = implode("id=",$x);
$parent[] = $r['firm'];
$list = implode("<a href='index.php?p=view&m=area&$xx'>", $parent)."</a>";
}
}
echo "<td><span>" . $list . "</span>/td>";
}
Thank you
first of all
$list = implode("<a h
should be
$list .= implode("<a h
That URL syntax is not the correct way to pass an array of values to a PHP script. It should use PHP array syntax for the parameter names. Also, you need separate your parameters with an ampersand (&):
http://page.com/index.php?p=view&m=area&id[]=173&id[]=552&id[]=76&8id[]=36&id[]=217
Then you can get the second one by using
$second_id = $_GET['id'][1]; // 552
etc.
FYI, you shouldn't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Neat and tidy way to solve php code?

How would i go about the following problem which involves running an update query for every row in the array defined below? I hope it becomes clear...
<?php
//Some code
user = array();
while ($row = mysql_fetch_array ($auctioncheck)){
$fdt[] = $row['finish_time'];
if ($date_time >= $fdt) {
$user[] = $row['current_bidder'];
{
{
I then want to update a table which sets the value as "user[]". What is the neatest way of doing this? I presume it requires a while loop only i don't know how to do it in this context. So it would be like...
<?php
//Above while loop and then...
$update = mysql_query("UPDATE homepage SET username = '$user[]'...so on");
Basically i want the update to be performed for every user[] in the above array. I might be able to figure it out if i knew how to determine the number of rows in the the user array. Any help would be much appreciated. Cheers.
It looks like the for each will come into play. Only i am now concerned with the elements of multiple arrays being used in the update.
$user = array();
$seller = array();
while ($row = mysql_fetch_array ($auctioncheck)){
$fdt[] = $row['finish_time'];
if ($date_time >= $fdt) {
$user[] = $row['current_bidder'];
$seller[] = $row['seller'];
}
}
$update = mysql_query("UPDATE homepage SET username = '$user[]'...WHERE username = '$seller'");
Any ides anyone for the multiple elements and arrays.
It should be $user = array();
Is this what you're looking for?
<?php
//Above while loop and then...
foreach($user as $value){
$update = mysql_query("UPDATE homepage SET username = '$value'");
}
?>
This is not PHP
user = array();
You are missing the $
Besides
where is
{
{
come into play?

Working with arrays in Kohana, Blank page?

tl;dr - Pushing an array (by $array[] or $array[$id] is not working in Kohana 3, it gives a blank white page.
I'm using Kohana (3), it's my first experience with MVC and it's been great so far; however, I'm working with a database and encountered a weird problem that I was hoping someone could shed some light on:
My workflow is like this, to give you an idea of my problems surrounding:
$sql = "SELECT table1.row1, max(table2.row1) as `maxAwesome` FROM table1, table2 WHERE table1.id=table2.table1id GROUP BY table1.id";
$table1Results = DB::query(Database::SELECT, $sql)->execute();
$masterArray = array();
foreach ($table1Results as $result1)
{
$sql = "SELECT * FROM table2 WHERE table2id='" . $result1['id'] . "' AND column > 21";
$table2Results = DB::query(Database::SELECT, $sql)->execute();
$subArray = array();
foreach ($table2Results as $result2)
{
$subArray[$result1['id']] = $result2;
// Even had just $subArray[] = array("whatever");
}
$masterArray[] = array("table1Data" => array(), "table2Data"=> $subArray);
}
I do a query where I run a couple max/min functions then do a query within the foreach doing another select to build a master array of data formatted the way I want it and all the SQL etc works fine and dandy; however, the problem arises when I'm pushing the array.
It seems whenever I push the array by doing either $array[] = array("data"); or by specifying the key $array[$id] = array("data"); Kohana gives me a straight blank page, no error, no output etc.
Sometimes I get a Kohana error indicating the key does not exist (duh, I'm creating it) but for the most part the output is straight white.
Why is this happening? Am I going about it wrong?
Thanks in advance.
Clarity edit:
My SQL blunders aside, the issue lies in the building of the secondary array, for example:
$queryStores = "SELECT stores.store_id, stores.title, max(product.discount) as `max_discount`, min(product.discount) as `min_discount`
FROM stores, products
WHERE products.store=stores.store_id
GROUP BY products.store";
$stores = DB::Query(Database::SELECT, $queryStores)->execute();
$formattedStores = array();
if (count($stores))
{
foreach ($stores as $store)
{
$formattedStores[$store['store_id']] = array(
"title" => $store['title'],
);
// Same result if just doing $formattedStores[] = array();
// Problem goes away should I do:
// $formattedStores = array("This works");
//
}
}
echo "<pre>";
print_r($formattedStores);
echo "</pre>";
That does not print an array, it simply gives a blank page; however, if i change it to just re-set the $formattedStores array to something I get an output. What is it about pushing the array that's causing a problem, perhaps a Kohana bug?
Thanks
Your code should be like:-
$sql = "SELECT table1.id, table1.row1, max(table2.row1) as `maxAwesome`
FROM table1, table2
WHERE table1.id = table2.table1id
GROUP BY table1.id";
$table1Results = DB::query(Database::SELECT, $sql)->execute();
$masterArray = array();
if (count($table1Results))
{
foreach ($table1Results as $result1)
{
$sqlInner = "SELECT * FROM table2
WHERE table2id = '" . $result1['id'] . "'
AND column > 21";
$table2Results = DB::query(Database::SELECT, $sqlInner)->execute();
$subArray = array();
if (count($table2Results))
{
foreach ($table2Results as $result2)
{
$subArray[$result1['id']] = $result2;
// Even had just $subArray[] = array("whatever");
}
}
$masterArray[] = array("table1Data" => array(), "table2Data"=> $subArray);
}
}
Some valuable coding standards & miss-ups:-
You have got the "id" field (w.r.t. the "table1" DB table) missing from the first SQL.
The second SQL should be better written using another variable naming, so as to keep it separate from the first one. Hence the second variable is named as "$sqlInner".
It's always better to check for any existence of array elements in an array variable, so I have used the simple checks using the "if" statement.
Hope it helps.
I've determined this to be memory related.

Fatal error, not quite sure why?

I think this is just something I haven't come across before!
$r = $database->currentChallengers($f, $g);
while($row=mysql_fetch_assoc($r))
{
$u[]=$row['username'];
$i[]=$row['userid'];
$s[]=$row['streak'];
}
for ($i = 0; $i < count($u); $i++)
{
foreach ($u as $user)
{
echo "Challenger: $u[$i]";
}
}
That PHP is for the following database query:
function currentChallengers($f, $g)
{
$q = "SELECT k.userid, k.streak, u.username
FROM ".TBL_KOTH." k
INNER JOIN ".TBL_USERS." u
ON k.userid = u.id
WHERE k.format = '$f' && k.game = '$g' && k.king = '0' && k.done = '0'
ORDER BY k.userid";
return mysql_query($q, $this->connection);
}
I am getting the error
Fatal error: [] operator not supported for strings
On the line
$u[]=$row['username'];
Could anyone tell me why this is happening?
Also, should the code I have written list each username from the query?
Thanks
The other answers already point out what you need to do: Use an array. But before that, check whether $u etc. are being used somewhere else in the code already. You could get in trouble because they may already be in use elsewhere - as strings.
And, you should really use some more verbose variable names to avoid building a maintenance nightmare. Why not use for example
$username[] = $row['username'];
$userid[] = $row['userid'];
$streak[] = $row['streak'];
}
PHP seems to be assuming your uninitialized variables are strings. See Pekka's Answer. Try initializing/declaring those variables before you start pushing values onto them.
$u = array();
$i = array();
$s = array();
Use meaningfull variable names.
You have used $u to store a string somewhere above this code.
Probably you stored a username in it.
So I recommend using variables $username and $users.
And set $users = array(); before a loop, as proposed by Mike/
What are you trying to do with $u[]=$row['username'];? $u is currently a string and you can't write to a specific index of a string (you haven't specified any index either).
If you're trying to store rows in to arrays, declare them as arrays and use an iterating variable to populate it.
$u = array();
$i = array();
$s = array();
$k = 0;
while($row=mysql_fetch_assoc($r))
{
$u[$k] = $row['username'];
$i[$k] = $row['userid'];
$s[$k] = $row['streak'];
$k = $k + 1;
}
Try this, instead of arrays :
$u=$row['username'];
$i=$row['userid'];
$s=$row['streak'];
Are you sure that $u is not already defined? Initialize it with $u = array(); before the first "while"...
The problem seems to come to the fact that $u (and possibly $s and $i) seems to be a string.
Try adding:
$u = array();
$s = array();
$i = array();
before:
$r = $database->currentChallengers($f, $g);
You should add $u = array() before accessing it. You probably use some other $u as a string in another part of your script and PHP still believe it's the same one.

Categories