Fatal error, not quite sure why? - php

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.

Related

using list() constructer for array

I have multiple dates to calculate on database. They are fetched and stored in an array.
How can I have variables for each of the returned values, since I don't know how many of the dates are returned?
Here is what I tried so far:
$get_status = $truckerController->status($gid);
$active_days = 0;
$active_d = array();
foreach ($get_status as $trucker) {
$active_d[] = $trucker->date;
}
list($date1, $date2) = $active_d;
So what I want is to have more than two or three parameters inside list() based on the array value size. Please help me out or suggest other ways to handle this issue.
Not sure if the whole approach is correct, but you can try with something like this.
$get_status = $truckerController->status($gid);
$active_days = 0;
$active_d = array();
$i = 0;
foreach ($get_status as $trucker) {
$i++;
$active_d["date".$i] = $trucker->date;
}
extract($active_d);
http://php.net/manual/en/function.extract.php

php - dynamic mysql_query in for loop from url array

I've looked for something similar on stack but nothing exactly as this.
I (think I) need to generate a unique MySQL query inside a loop as each iteration needs to look up a different table. the loop is from an exploded $_GET array.
The problem is creating a differently named mysql query based on the loop iteration. I've done it where the $var name is different but it doesn't work, I think because it is a string not a variable?
Any help appreciated
$temps = explode(",", $_GET['temps']);
$tempCount = count($temps);
for ($i=0; $i<$tempCount; $i++)
{
/*'normal' database lookup
$check = mysql_query("SELECT * FROM _db_".$temps[$i]."");
$checks = array();
while ($row = mysql_fetch_assoc($check)) {
$checks[] = $row;
}*/
//here's where I'm trying to build a 'dynamic' lookup for each loop iteration
$checkTemp=$check.$temps[$i];
$checkTempArray=$check.$temps[$i].'Array';
$checkTemp = mysql_query("SELECT * FROM _db_".$temps[$i]."");
$checkTempArray = array();
while ($row = mysql_fetch_assoc($checkTemp)) {
$checkTempArray[] = $row;
}
}
If I understand correctly you're trying to SELECT * from all tables seperated by , in the $_GET["temps"]
$temps = explode(",", $_GET['temps']);
$tempCount = count($temps);
$allResults = array();
for ($i=0; $i<$tempCount; $i++)
{
$checkTemp = mysql_query("SELECT * FROM _db_".mysql_real_escape_string($temps[$i]));
$allResults[$temps[$i]] = array();
while ($row = mysql_fetch_assoc($checkTemp))
{
$allResults[$temps[$i]][] = $row;
}
}
// Now for example $allResults["john"][3] contains the fourth row in the table _db_john
print_r($allResults["sally"][2]); // print the third row in _db_sally
Seems like a typo in your code
$checkTemp = mysql_query("SELECT * FROM db".$temp[$i]."");
either use
$temps[$i] or just $temp
$temp[$i] doesn't makes any sense
so your query should be instead
$checkTemp = mysql_query("SELECT * FROM db".$temps[$i]."");
EDIT:
for your array part you can use
$$temp = array();
while ($row = mysql_fetch_assoc($checkTemp)) {
$$temp[] = $row;
}

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?

Make array with arrays from a mysql query

Working on a e-shop, i must read from the DB the products that have productpack not null.
productpack from the DB looks like this : 0141,3122,0104,0111,3114,0106,0117 .
I'm trying to get all the DB items that have productpack set (not null), and make them into an array with arrays with those codes (0141,3122,0104,0111,3114,0106,0117).
function p_productpacks(){
$productpacks = array();
$pack = array();
$q = mysql_query('SELECT productpack FROM products WHERE productpack <> "";');
while($p = mysql_fetch_object($q)){
$pack = explode(",", $p);
$productpacks[] = $pack;
}
return $productpacks;
}
You need to create an array otherwise, you're overwriting existing packs:
$pack = explode(",", $p->productpack);
$productpacks[] = $pack;
For more information read about array_pushDocs and PHP Arrays Docs (and mysql_fetch_objectDocs).
You can get all productpacks in a CSV array using:
$result = mysql_query("SELECT GROUP_CONCAT(productpack) as productpacks
FROM products WHERE productpack <> '' ");
if ($result) {
$row = mysql_fetch_row($result);
$productpacks_as_CSV_string = $row['productpacks'];
}
That way you only need to get one row out of the database, saving lots of time.
See: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
mysql_fetch_object returns an object and can't be used with string processing.. if you definitely want to use this, you need to do something like:
$pack=explode(',',$p->productpack);
$productpacks[]=$pack
Or, to use a good old array instead:
while ($p = mysql_query($q))
{
$pack = explode(",", $p['productpack']);
$productpacks[] = $pack;
}

PHP 1-liner each() with mysql_fetch_assoc()

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));

Categories