How to convert string to variable for use in server code - php

I want convert $RowNumber from string to a variable, for use in while, do is that possible?!how to do it?
$row1 = mysqli_query($Database,"SELECT * FROM Table1 ORDER BY ID");
$row2 = mysqli_query($Database,"SELECT * FROM Table2 ORDER BY ID");
// Others Rows code
for ($num = 1; $num <= 6; $num++)
{
$RowNumber = "row" . $num; // Save RowNumber for use in while
echo '<tr>';
// when it's used it not work becuse it's just a string only and
// i want convert it to variable to use in while
while($row = mysqli_fetch_array($RowNumber))
{
echo '<td>
<div class="Image_DIV" id="'; echo $row['DIV_ID']; echo '">
<table>
<tr><td class="Image"><img class="ImageOfDiv"
src="3DGallery/Chosen/Small/'; echo $row['src']; echo '"/></td></tr>
<tr>
<td class="ImageDescribe">'; echo $row['describe']; echo '</td></tr></table>
</div>
</td>';
}
echo '</tr><tr>';
}

Try ${$RowNumber} instead of $RowNumber for your purpose, If you need more info you can find it here. But as Mr. raina77ow has commented arrays are a good option.

If Table1 and Table2 have the same columns then you should UNION them together in your SQL then work on a single results set.
$results = mysqli_query($Database, "SELECT ID, DIV_ID, src, describe FROM `Table1` UNION SELECT ID, DIV_ID, src, describe FROM `Table2` ORDER BY ID");
echo '<tr>';
$x = 0;
while($row = mysqli_fetch_array($results))
{
echo '<td>';
echo $row['DIV_ID'];
echo $row['src'];
echo $row['describe'];
echo '</td>';
if( ++$x % 3 == 0 ) {
echo '</tr><tr>';
}
}
echo '</tr>';

Try this:
$rows[] = mysqli_query($Database,"SELECT * FROM Table1 ORDER BY ID");
$rows[] = mysqli_query($Database,"SELECT * FROM Table2 ORDER BY ID");
// Others Rows code
foreach ($rows as $current)
{
echo '<tr>';
// loop the query
while($row = mysqli_fetch_array($current))
{
echo '<td>
<div class="Image_DIV" id="'; echo $row['DIV_ID']; echo '">
<table>
<tr><td class="Image"><img class="ImageOfDiv"
src="3DGallery/Chosen/Small/'; echo $row['src']; echo '"/></td></tr>
<tr>
<td class="ImageDescribe">'; echo $row['describe']; echo '</td></tr></table>
</div>
</td>';
}
echo '</tr><tr>';
}
You cant assign variables like that without using php Eval: http://www.php.net/eval, but that is realy bad practise!
or using ${$var} syntax. But arrays is probably easier to work with.

Related

MySql While loop taking too long to query

just wondered if there was a a faster way of running this query? I have over 250K rows in my 'results' table. The code searches the table for all of the different types of race a trainer has run. It the looks at how many races that trainer has ran in the type of race. Then it looks at hoe many races he/she has won. Hope this is enough information. Thanks for looking.
echo "<div style='text-align:center;'>";
echo "<table id='main_table'>";
echo "<tr ><td align = center colspan = 4>".$trainer."</td></tr>";
$result = mysqli_query($db,"SELECT
DISTINCT RaceType AS racetype
FROM results
WHERE trainer = '$trainer' ORDER BY RaceType ASC"); //placing_numerical,
while($row = mysqli_fetch_array( $result ))
{
echo "<tr>";
echo "<td>";
echo $row['racetype'];
echo "</td>";
echo "<td>";
$result_horse = mysqli_query($db,"
SELECT
COUNT(id) AS result_run
FROM results
WHERE trainer = '$trainer' AND RaceType = '".$row['racetype']."'
");
$row_horse = mysqli_fetch_array( $result_horse );
echo $row_horse['result_run'];
$a = $row_horse['result_run'];
echo "</td>";
echo "<td>";
$result_horse1 = mysqli_query($db,"
SELECT
COUNT(id) AS result_win
FROM results
WHERE trainer = '$trainer' AND RaceType = '".$row['racetype']."' AND placing_numerical = '1'
");
$row_horse1 = mysqli_fetch_array( $result_horse1 );
echo $row_horse1['result_win'];
$b = $row_horse1['result_win'];
echo "</td>";
echo "<td>";
$percent = ($b / $a ) * 100;
$percent = sprintf('%0.0f', $percent);
echo $percent."%";
echo "</td>";
echo "</tr>";
}
echo "</table>";
Here are two suggestions you can check :-
For row_horse and row_horse1 , use "mysqli_fetch_assoc" instead of "mysqli_fetch_array" .
Try to write a single query taking all the three queries and it will save you more time what you are expecting .

MySQL select where column LIKE and is not empty

I have the following query and I'm trying to select only the rows where I have picture.
In table kat_gl_picture I have 3 categories, but I don't have picture in all 3 categories yet!
All work just fine, but I have printed name of third category, where I don't have picture.
I tried WHERE link LIKE '%$first_var%'AND NOT (link <=> NULL)
....IS NOT NULL - but nothing yet worked.
Tabele1 and 2 and web problem solved
<?
include("connection.php");
$kategorije = mysql_query("SELECT * FROM kat_gl_picture ORDER BY rbr");
while ($red=mysql_fetch_array($kategorije))
{
$first_var = $red['kat'];
$result = mysql_query("SELECT id, naziv, ime, tekst, username, link, file_name, datum FROM Tab_Pic_Pic
WHERE link LIKE '%$first_var%'
ORDER BY id");
echo '<table>';
echo '<tbody>';
echo $first_var;
echo '<tr>';
echo '<TD valign="top">';
while ($row=mysql_fetch_array($result))
{
list($x, $y) = getimagesize("admin /upload/".$row['file_name']);
if ($x>$y) {
$y=($y/$x)*150;
$x=150;
}
else
{
$x=($x/$y)*115;
$y=115;
}
$ID_broj = $row["id"];
$tekst_broj = $row["tekst"];
?>
<? echo '<img src="admin /upload/'.$row['file_name'].'" height="'.$y.'" width="'.$x.'"/>';?>
<?
}
echo '</td>';
echo '</tr>';
echo '</tbody>';
echo '</table>';
}
The problem is that I cannot determine if there is a foreign key in your Tab_Pic_Pic table. You can however join on a LIKE.
Try this:
SELECT * FROM Tab_Pic_Pic JOIN kat_gl_picture ON Tab_Pic_Pic.link LIKE CONCAT('%', kat_gl_picture.kat, '%') ORDER BY kat_gl_picture.kat, Tab_Pic_Pic, rbr
It should give you a list of all pictures including the kat_gl_picture.kat field which you can just use a local variable to detect change.
Would be easier to provide a more accurate example if I had the full table info. Standard method is to have a foreign key in Tab_Pic_Pic that references the corresponding primary key from the kat_gl_picture table.
Alternatively, if you simply want to omit the blank category it can be done in your PHP code like this:
if(mysqli_num_rows($result)>0){
echo '<table>';
echo '<tbody>';
echo $first_var;
echo '<tr>';
echo '<TD valign="top">';
while ($row=mysql_fetch_array($result))
{
list($x, $y) = getimagesize("admin /upload/".$row['file_name']);
if ($x>$y) {
$y=($y/$x)*150;
$x=150;
}
else
{
$x=($x/$y)*115;
$y=115;
}
$ID_broj = $row["id"];
$tekst_broj = $row["tekst"];
?>
<? echo '<img src="admin /upload/'.$row['file_name'].'" height="'.$y.'" width="'.$x.'"/>';?>
<?
}
echo '</td>';
echo '</tr>';
echo '</tbody>';
echo '</table>';
}
Wrapping the output of your HTML in a simple condition like this should illustrate that the script itself is inefficient. Trust me when I say it can all be accomplished with one query. Do not get frustrated. You'll figure it out. Programming is hard.

PHP For Loop dynamic from database

I'm generating my check boxes from this code. But, I'm having difficulty with making it generate by 5 outputs then once the 5th output is displayed it should skip to the next line.
Would appreciate any help.
<?php
$result=mysql_query("SELECT * FROM tbl_tourism_type order by type_name ");
while($row = mysql_fetch_array($result))
echo '<input type="checkbox" name="type" value='.$row['type_id'].'>'
.'<label>'.$row['type_name']. '</label>'.'<br>'.'<br>';
?>
<?php
$result=mysql_query("SELECT * FROM tbl_tourism_type order by type_name ");
$i=1;
while($row = mysql_fetch_array($result))
{
echo '<input type="checkbox" name="type" value='.$row['type_id'].'><label>'.$row['type_name']. '</label>';
if($i%5==0)
{
echo "<br>";
}
$i++;
}
?>
$result = mysql_query("SELECT * FROM tbl_tourism_type order by type_name ");
$i=0;
while($row = mysql_fetch_array($result)){
if($i%5 == 0){
//skip to next line
//continue??
}
echo '<input type="checkbox" name="type" value='.$row['type_id'].'>'.'
<label>'.$row['type_name']. '</label>'.'<br>'.'<br>';
$i++;
}
Do like this
<?php
$i =1;
$result=mysql_query("SELECT * FROM tbl_tourism_type order by type_name ");
while($row = mysql_fetch_array($result)){
if($i == 5){
echo "<br>";
$i = 1;
}
else
echo '<input type="checkbox" name="type" value='.$row['type_id'].'>'
.'<label>'.$row['type_name']. '</label>';
$i++;
}
?>
You question is how to skip every 5th entry and to put a linebreak instead?
Have a try like this:
<?php
$i=0;
$result=mysql_query("SELECT * FROM tbl_tourism_type order by type_name ");
while($row = mysql_fetch_array($result))
{
if (++$i % 5)
echo sprintf ( '<input type="checkbox" name="type" value="%s">'
.'<label>%s</label>'."\n",
htmlentities($row['type_id']),
htmlentities($row['type_name']) );
else
echo "<br>\n";
}
?>
In addition to iterating over all entries in the result just use a counter you increment with every iteration. Then, inside the iteration, only output the current entry if the counter modulo 5 is not zero. So if it is not a clean multiple of 5.

Using PHP foreach to get mysql table data

ive got 1 database table contains row:
TABLE FROM reservations:
attandee01
attandee02
attandee03
attandee04
attandee05
attandee06
PHP CODE:
$q = $db->query("SELECT * FROM bs_events
LEFT JOIN bs_reservations ON bs_reservations.id_event = bs_events.id");
while($r = $q->fetch_array(MYSQLI_ASSOC)):
echo '<td>' . $r['attandee1'] . '</td>';
echo '<td>' . $r['attandee2'] . '</td>'
echo '<td>' . $r['attandee3'] . '</td>'
endwhile;
or is there any simple way using foreach to echo attandee1 - attandee10?
$q = $db->query("SELECT * FROM bs_events
LEFT JOIN bs_reservations ON bs_reservations.id_event = bs_events.id");
while($r = $q->fetch_array(MYSQLI_ASSOC)):
foreach($r as $value) {
echo '<td>' . $value . '</td>';
}
endwhile;
Should echo each column value per table row.
EDIT: If you only want the attendees:
$q = $db->query("SELECT * FROM bs_events
LEFT JOIN bs_reservations ON bs_reservations.id_event = bs_events.id");
while($r = $q->fetch_array(MYSQLI_ASSOC)):
for($i = 1; $i < 11 $i++) {
echo '<td>' . $r['attendee'.$i] . '</td>';
}
endwhile;
you can use foreach, of course, as $r is a regular array and can be iterated using foreach() operator. Did you try it?
However, looking at the field names, I suspect serious design flaw in your data structure.
It seems attandees should be stored in another table.
You may also consider using templates. Printing data directly from the database loop is very bad practice. You have to get all your data first and only then start printing it out.
Well yes:
for($i=1; $i<11; ++$i) {
echo "<td>".$r["attandee".$i]. "</td>";
}
But that is columns, what you want is the row based solution for that I'd use something like:
for($r=$q->fetch_assoc(); !is_null($r); $r= $q->fetch_assoc()) {
echo "<td>".array_pop($r)."</td>"; // output the only element in the array?
}
$q->free(); // don't forget to free the memory of the result set!
don't know if i understood your question... is this what you're looking for:
while($row = $q->fetch_array(MYSQLI_ASSOC)):
foreach($row as $field){
echo '<td>' . $field . '</td>';
}
endwhile;
Not really sure if this is what you are looking for, but give it a shot:
while($r = $q->fetch_array(MYSQLI_ASSOC)) {
foreach($r as $value) {
echo '<td>' . $value . '</td>';
}
}
As example you can use alternate syntax.
<table>
<?php foreach ($mysqli->query($sql) as $row ): ?>
<tr><td><?php echo $row['row_name1']; ?></td><td><?php echo $row['row_name2']; ?></td></tr>
<?php endforeach; ?>
</table>

displaying values from database into an html table

i want to display values from a database (a list of categories) into a table that has 2 columns and x number of rows.
I want my web page to display like this:
Apes Cats
Apples Cherries
Bats Tigers
Berries Zebras
Instead of
Apes Apples
Bats Bears
Cats Cherries
Tigers Zebras
Here is my code so far:
<table border="0" bordercolor="#FFCC00" style="background-color:#FFFFCC" width="400" cellpadding="3" cellspacing="3">
<?php
$query = "SELECT * FROM category ORDER BY cat_name";
$data = mysqli_query($dbc, $query);
while ($category = mysqli_fetch_array($data)) {
?>
<tr>
<td><?php echo $category['cat_name'] ?></td>
</tr>
<?php } ?>
</table>
Here's the basic idea:
You get the count of the data via num_rows
Divide by two.
Now, the result of your division will be the number of rows.
Output a loop echoing value for row x and x+ num rows. For example the output of line 1 would be :
<tr><td>$row[val1][data]</td><td>$row[val5][data]</td></tr>
So, your loop would ultimately output:
val 1 | val 5
val 2 | val 6
val 3 | val 7
val 4 | val 8
The loop should end when your incrementing variable = num_rows. Should be pretty straightforward from there. Good luck.
Try this (haven't tested it though):
<table border="0" bordercolor="#FFCC00" style="background-color:#FFFFCC" width="400" cellpadding="3" cellspacing="3">
<?php
$query = "SELECT * FROM category ORDER BY cat_name";
$data = mysqli_query($dbc, $query);
# Calculate total rows and half rows, rounded up
$full_row_count = mysqli_num_rows($data);
$half_row_count = ceil($full_row_count / 2);
$i = 0;
while ($i <= $half_row_count) {
# Set the result pointer for first column ...
mysqli_data_seek($data, $i);
$category_1 = mysqli_fetch_array($data);
# ... then calculate the offset for the second column ...
$col_2_offset = $i + $half_row_count;
# .. and make sure it's not larger than total rows - 1
if ($col_2_offset <= $full_row_count - 1) {
mysqli_data_seek($data, $col_2_offset);
$category_2 = mysqli_fetch_array($data);
} else {
$category_2 = array('cat_name' => '');
}
?>
<tr>
<td><?php echo $category_1['cat_name'] ?></td>
<td><?php echo $category_2['cat_name'] ?></td>
</tr>
<?php
$i++;
}
?>
</table>
Hope this helps !
You can add an another variable say, $i, to the loop and just increment this through as follows:
<table border="0" bordercolor="#FFCC00" style="background-color:#FFFFCC" width="400" cellpadding="3" cellspacing="3">
<?php
$query = "SELECT * FROM category ORDER BY cat_name";
$data = mysqli_query($dbc, $query);
$i=1;
while ($category = $data->fetch_row()) {
?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $category[1] ?></td>
</tr>
<?php
$i++;
} ?>
</table>
EDIT: Updated to fetch row data for each result and assume that cat_name is the second item in the array i.e. $category[1].
If it doesn't have to be a table and your fine with browsers that support CSS 3, then you can use CSS columns:
http://jsfiddle.net/QKuDL/
Otherwise you'll need to sort the results first (untested - PHP is not my strong suit):
<?php
$query = "SELECT * FROM category ORDER BY cat_name";
$data = mysqli_query($dbc, $query);
$col_count = 2;
$max_items_per_col = ceil( mysqli_num_rows ( $data ) / $col_count );
$cols = array(array());
$col = 0;
while ($category = mysqli_fetch_array($data)) {
if (count($cols[$col]) >= $max_items_per_col) {
$col++;
}
$cols[$col][] = $category['cat_name'];
}
?>
<table> <!-- all of those attributes should be CSS instead -->
<?php for ($i = 0; $i < $max_items_per_col; $i++) { ?>
<tr>
<?php foreach ($cols as $col) { ?>
<td><?php if(isset($col[$i])) echo $col[$i]; ?></td>
<?php } ?>
</tr>
<?php } ?>
</table>
<?php
$query = "SELECT * FROM category ORDER BY cat_name";
$data = mysqli_query($dbc, $query);
$midpoint = ceil($data->num_rows / 2);
$i=0;
while ($category = $data->fetch_array()) {
if ($i < $midpoint)
$left[$i] = "<td>" . $category['cat_name'] . "</td>";
else
$right[$i - $midpoint] = "<td>" . $category['cat_name'] . "</td>";
$i++;
}
print "<table>";
for ($j=0; $j < $i; $j++)
{
print "<tr>" . $left[$j];
if (array_key_exists($j, $right)) print $right[$j];
print "</tr>";
}
print "</table>";

Categories