Undefined offset when printing elements of an array - php

I have this code:
$items_query = mysql_query('SELECT * FROM Items_Orders NATURAL JOIN Items
WHERE order_id="'.$order->order_id.'"');
if(!$items_query)
{
echo 'MySQL error: '.mysql_error();
die();
}
//add each item to the order
while($items_row = mysql_fetch_array($items_query))
{
echo "item: ";
for($i = 0; $i < count($items_row); $i++)
{
echo $items_row[$i];
}
}
When the elements of the items_row are printed, my code iterates beyond the bounds of items row. I am confused at why this is. I explicitly define i to only iterate up to the size of items_row. What's going on here?

You are counting double length, because by default, you are getting named an numbered values. Try the following
while($items_row = mysql_fetch_array($items_query, MYSQL_NUM))
{
echo "item: ";
for($i = 0; $i < count($items_row); $i++)
{
echo $items_row[$i];
}
}
See offical docs
P.S. mysql_* is deprecated, look into PDO object.

Try this:
while($row = mysql_fetch_array($query,MYSQL_NUM)){
$count = count($row);
for($i = 0;$i < $count;$i++){
echo $row[$i];
}
}
But your code is very dirty, why you do not use PDO ? Is the fast way how to make escaped queries... PDO manual

Related

Getting variables after Randomly selecting two rows in PHP

I am using following code
$con=mysql_connect('localhost','admin',"password");
$db=mysql_select_db('DbName',$con);
$query="SELECT COUNT(shuffel.clientid) as total_users FROM shuffel";
$result=mysql_query($query);
$total=mysql_fetch_array($result);
$total =$total['total_users'];
if($total>=2)
{
$result=$total/2;
$length =round($result);
if ($length > 10)
$length = 10;
for($i = 0; $i < $length; $i++)
{
$data = "SELECT * FROM shuffel ORDER BY RAND() LIMIT 2";
$shuffeluser = mysql_query($data);
int count = 0;
while($row = mysql_fetch_assoc($shuffeluser))
{
$my_array[] = $row;
count ++;
}
}
Now i want to get something like
$firstUserId = $my_array[0]->id;
However Everhthing just returns empty.
What is wrong in above code
mysql_fetch_assoc() returns array, not object so go get id you should use $my_array[0]['id'].
Also think about moving to PDO or mysqli_* because mysql_* is deprecated.

PHP loop X amount of times

I have a string called $columns which dynamically gets a value from 1 to 7. I want to create a loop of <td></td> for however many times the value of $columns is. Any idea how I can do this?
for ($k = 0 ; $k < $columns; $k++){ echo '<td></td>'; }
Here's a more readable way to achieve this:
foreach(range(1,$columns) as $index) {
//do your magic here
}
If you just need to use number of repeat count:
for ($i = 0; $i < 5; $i++){
// code to repeat here
}
just repeat $n times? ... if dont mind that $n goes backwards...
the advantage is that you can see/config "times" at the beginning
$n = 5;
while (--$n >= 0)
{
// do something, remember that $n goes backwards;
}
I like this way:
while( $i++ < $columns ) echo $i;
Just bear in mind if $columns is 5, this will run 5 times (not 4).
Edit: There seems to be some confusion around the initial state of $i here. You are welcome to initialise $i=0 beforehand if you wish. This is not required however as PHP is a very helpful engine and will do it for you automatically (tho, it will throw a notice if you happen to have those enabled).
There is a str_repeat() function in PHP, which repeats a string a number of times. The solution for your problem would be:
str_repeat( '<td></td>', $columns );
If $columns is a string you can cast to int and use a simple for loop
for ($i=1; $i<(int)$columns; $i++) {
echo '<td></td>';
}
A for loop will work:
for ($i = 0; $i < $columns; $i++) {
...
}
You can run it through a for loop easily to achieve this
$myData = array('val1', 'val2', ...);
for( $i = 0; $i < intval($columns); $i++)
{
echo "<td>" . $myData[$i] . "</td>";
}
Why use logic at all, don't waste those CPU cycles!
<td colspan="<?php echo $columns; ?>"></td>

there's any way to use foreach with AND?

foreach(($_POST["msg"] as $mg) AND ($_POST["control"] as $id))
{
echo $mg;
echo $id;
}
i need make something like that, any way to do? i'm trying to get 10 mysql records and edit all of them
No, that won't work. The closest thing I can see to what you're trying to do is:
for($i = 0; $i < count($_POST["msg"]); $i++) {
echo $_POST["msg"][$i];
echo $_POST["control"][$i];
}
Assuming that "msg" and "control" will always contain the same amount of items.
Assuming both $_POST['msg'] and $_POST['control'] are actually arrays, have numeric keys (thanks #iMoses), and have the same length, you could use a for loop -
for ($i = 0; $i < count($_POST["msg"]); $i++){
$mg = $_POST['msg'][$i];
$id = $_POST['control'][$i];
}

PHP variable additions

Hey does anyone know a reason why this is not working? its not calculating any of the additions and just entering 0 into the database. Any help would be great, thank you!.
$member_id = //users member id in database//
$track = //the track results being updated//
$engine = //the engine id from the members table in database//
$engine_points_system = array();
$engine_points_system["qualpos1"] = 30;
$engine_points_system["qualpos2"] = 20;
$engine_points_system["qualpos3"] = 18;
$engine_points_system["qualpos4"] = 17;
$engine_points_system["qualpos5"] = 16;
$enginepoints = 0;
$qualifyingpoints = 0;
$results_query = mysql_query("SELECT pos_1, pos_2, pos_3, pos_4, pos_5
from engine_qualifying_results WHERE track_id = '$track'")
or die ("Failed to update" . mysql_error());
$row = mysql_fetch_array($results_query);
$enginequalifying = array();
for ($i = 1; $i <= 5; $i++) {
$enginequalifying["pos$i"] = $row['pos_$i'];
}
for($i = 1; $i <=5; $i++) {
if($engine == $enginequalifying["pos$i"]){
$enginepoints += $engine_points_system["qualpos$i"];
$qualifyingpoints += $engine_points_system["qualpos$i"];
}
}
$results_query = mysql_query("INSERT INTO member_results (member_id, engine_points)
VALUES ('$member_id', $enginepoints')")
or die ("Failed to update" . mysql_error());
$enginequalifying["pos$i"] = $row['pos_$i'];
In this line you have 'pos_$i'. This is the literal string 'pos_$i'. You should use "pos_$i" instead.
$enginequalifying["pos$i"] = $row["pos_$i"];
UPDATE:
In your code $enginequalifying is redundant, and not needed. You can just use $row in its place.
for($i = 1; $i <=5; $i++){
if($engine == $row["pos_$i"]){
$enginepoints += $engine_points_system["qualpos$i"];
$qualifyingpoints += $engine_points_system["qualpos$i"];
}
}
Also, as #ax. points out, you have an extra ' (or a missing ') in your INSERT.
$results_query = mysql_query("INSERT INTO member_results (member_id, engine_points)
VALUES ('$member_id', '$enginepoints')")
or die ("Failed to update" . mysql_error());
Look at this code:
<?php
$i = 5;
print "i is $i";
print "\n";
print 'i is $i';
?>
You'd expect it to print:
i is 5
i is 5
But instead, it will print:
i is 5
i is $i
This happens because when the string is wrapped in single quotes, $i is not evaluated. It is just the string $i.
To fix the code, try replacing this line:
$enginequalifying["pos$i"] = $row['pos_$i'];
With this line:
$enginequalifying["pos$i"] = $row["pos_$i"];
Quotes make a difference.
And by the way, ESCAPE YOUR SQL!!!. Please?
Not an answer, but too ugly to put into a comment: You could bypass the entire loop to build the enginequalifying array by simply doing:
SELECT pos_1 AS pos1, pos_2 AS pos2, etc...
for your query, then simply having:
$enginequalifying = mysql_fetch_assoc($result);
It's a waste of CPU cycles to have PHP fetch/rename database fields for you when a simple as alias in the original query string can accomplish the exact same thing.
And incidentally, this will also remove the string-quoting error you've got that Rocket pointed out in his answer.
I dont think it is possible to say without knowing what you have in your database.
But I can tell you that you have a syntax error in the last SQL query ($enginepoints ends with a quote).

PHP loop to sort table

I'm querying a database for names that are numbered 1-26 alphabetically. I have the following code, but since HTML is structured tr then td, the table appears alphabetically by row as opposed to by column. How can I make it appear in order by column?
$query = mysql_query("SELECT name FROM people WHERE main=1 ORDER BY id");
$i = 0;
while($result = mysql_fetch_array($query)) {
$name = $result['name'];
if ($i % 5 == 0) echo "<tr>\n";
echo "<td width=\"150\">";
echo "".$name."<br />";
echo "</td>\n";
$i++;
if ($i % 5 == 0) echo "</tr>\n";
};
alpha beta charlie
delta echo foxtrot
vs.
alpha charlie echo
beta delta foxtrot
Also, I'm open to reworking the code if there's a more efficient way.
You could just access the output array in strides. Compute how many rows you need as the number of results divided by 5, and use the row count as the stride.
$ncols = 5;
$nrows = $nresults / $ncols + ($nresults % $ncols == 0 ? 0 : 1);
for ($i = 0; $i < $nrows; $i++)
{
// start row
for ($j = 0; $k < $ncols; $j++)
{
// print $results[$nrows * $j + $i]
}
// end row
}
You'll have to transfer your query results into an array $results first. Since you'll have to know the total number of results, this is sort of mandatory, though I'd be curious if anyone has a solution that can work while fetching the results.
Update: See Justin's answer for a cool solution that grows the output while fetching the query results line by line. Since it's currently being worked on, here's a summary (credits to Justin):
$nresults = mysql_num_rows($query);
$ncols = 5;
$nrows = (int) ceil($nresults / $ncols);
$i = 0; $cols = array_fill(0, $nrows, "");
while ($result = mysql_fetch_array($query))
$cols[$i++ % $nrows] .= "<td>$result['name']</td>";
echo "<tr>" . implode("</tr><tr>", $cols) . "</tr>";
Edit:
After the discussion in the comments between myself, Kerrek SB and the OP bswinnerton, the following code seems to be the most effective:
$columns = 3;
$rowcount = mysql_num_rows($query);
$rows = ceil($rowcount / $columns);
$rowdata = array_fill(0, $rows, "");
$ctr = 0;
while ($result = mysql_fetch_array($query))
$rowdata[$ctr++ % $rows] .= '<td>'.$result['name'].'</td>';
echo '<tr>'.implode('</tr><tr>',$rowdata).'</tr>';
This will create three columns, filled vertically (my original answer would create three rows). It also properly initializes the array (preventing PHP warnings), yields a correct row count for result counts that aren't divisible by the column count, and incorporates Kerrek's clever "calc-row-in-the-subscript" trick.
Original Post:
You could use arrays and implode() This way, you only have to make one pass through your results:
$row = 0;
$rows = 3;
$rowdata = array();
while($result = mysql_fetch_array($query))
{
if ($row >= $rows) $row = 0;
$rowdata[$row++] .= '<td>'.$result['name'].'</td>';
}
echo '<tr>'.implode('</tr><tr>',$rowdata).'</tr>';

Categories