HI my code isn't working and I get this error when the code is run:
Picture of error
This is line 110 of the code:
$results = array_merge($results, $game_list[$row][$col]);
And this is the rest of the code:
$results = array();
for ($row = 0; $row < $num_rows; $row++){
if (strstr($game_list[$row][2], $search) or strstr($game_list[$row][3], $search)){
for ($col = 0; $col < count($game_list[$row]); $col ++) {
$results = array_merge($results, $game_list[$row][$col]);
$successful = true;
}
}
}
if ($successful == true){
echo "<table>
<tr>
<th>Game ID</th>
<th>Genre</th>
<th>Game Name</th>
<th>Game Description</th>
<th>Rental Cost Per Day</th>
</tr>";
// Set number of table rows
$num_rows = count($results) - 1;
// Set number of table columns
$num_cols = 5;
// Start loop to generate rows
for($row = 0; $row < $num_rows; $row++) {
// Generate row HTML
echo "<tr>";
//Start loop to generate columns (nested FOR loop!)
for($col = 0 ; $col < $num_cols; $col++) {
// Generate column HTML
echo "<td>". $results[$row][$col] ."</td>";
}
// End of columns loop
// Generate end of row HTML
echo "</tr>";
}
echo "</table>";
The code is meant to search through the array game_list and see if a keyword a user has entered is in the array. If it is, then the code will take the whole row in the array game_list and add it to the array results. This array will then be displayed in a table to the user.
If anyone can give me a fix that would be great.
The reason for that error is, that you try to merge an array with a string,
array_merge takes two arrays as arguments.
I'd suggest not to use array_merge() at all, but simply add the requested data to the results array:
<?php
$results = Array();
...
$results[] = $game_list[$row];
...
?>
Related
I need some PHP code to display all columns (without referencing how many there are, or their names) in a comma separated, one row per line, format.
I am a novice and have only ever worked with examples where I reference the columns by name:
$result = mysql_query("select * from table1");
while($row = mysql_fetch_array($result))
{
echo $row["field1"].','.$row["field2"];
}
In the above code, can I create a looping echo command based on the number of columns (how do I get this value?) to print all the columns – if I can display the column names in the first row of output, great, but it’s not essential. Or, is there a specific command that will achieve the same result?
I think the answer is a foreach($row as....) - but not sure where to go from there.
Yep you can do a foreach but if you just want to display your values in a CSV style you can do :
$firstRow = true;
while($row = mysql_fetch_array($result))
{
if ($firstRow) {
$firstRow = false;
$columns = array_keys($row);
// prints all the column names
echo implode(',', $columns);
}
// print all the values
echo implode(',', $row);
}
If you want more control over what you output you can use a foreach :
while($row = mysql_fetch_array($result))
{
foreach ($row as $column => $value) {
echo $column.' : '.$value."\n";
}
}
You'll want to count the $row array
while($row = mysql_fetch_array($result))
{
$columns = count($row);
for($i = 0; $i < $columns; $i++)
{
echo $row[$i].',';
}
}
Or you can use foreach() as #Dagon has pointed out -
while($row = mysql_fetch_array($result))
{
foreach($row as $column)
{
echo $column . ',';
{
}
Please, stop using mysql_* functions. They are no longer maintained and are officially deprecated. Learn about prepared statements instead, and consider using PDO.
Basically what I'm doing is storing everything from my table into an array.
After that I go through it and select row by row and assign it to an array.
Then it goes through that array and puts it in the table, cell by cell, in a single row.
Now the last column of my table are links and they are the fourth and last column in the table and in the database. They're, just like they should, showing up as plain text, but I'd rather have them clickable (For ease of use).
Since the entire table (Except for the, in this case, 4 header items) is created by php code I would have no clue on how to change just the last bit to be a link.
Help would really be appreciated!
Code:
$sql = "SELECT * FROM Future_Mods";
$result = mysqli_query($conn, $sql) or die (mysql_error());
echo "<table>";
echo "<tr>
<th>ID</th>
<th>Mod</th>
<th>Is Available</th>
<th>Has Been Added</th>
<th>Reason</th>
</tr>";
for($i = 0; $i < mysqli_num_rows($result); $i++) {
echo "<tr>";
$row_array = mysqli_fetch_row($result);
for ($j = 0; $j < mysqli_num_fields($result); $j++) {
echo "<td>" .$row_array[$j]. "</td>\n";
}
}
echo "</table>";
Relatively simple:
while ($row = mysqlI_fetch_row($result)) {
end($row); // move array pointer to end of array
$key = key($row); // get key of current pointer element
// update last item to be a link
$row[$key] = '', $row[$key], '';
// dump out array as table cells
echo '<td>', implode('</td><td>', $row), '<td>';
}
This is a question of HTML formatting for your result set table.
If you happen to have a php variable $s that you are sure contains a URL, you can display the URL and make it clickable with php code like this:
echo sprintf ('$1', $s);
For example if $s has the value http://stackoverflow.com/ this will yield the HTML text
http://stackoverflow.com/
One of your $row items will contain that URL. So you can render it with this sort of patten.
This question already has answers here:
MySQL query to get column names?
(22 answers)
Closed 9 years ago.
I am attempting to retrieve the column headers for html headers from a MySQL query. The structure of my application is such that the column headers aren't static (sometimes there are 4, sometimes 7, etc.) For some unbearable reason I can't find a simple way to get the column names from any given query.
My end goal is to output an html table from the query.
Well if you get the query as an associative array, you can do something like this:
$query = "Select [stuff]";
$results = mysql_query($query);
$i = 0;
while ($row = mysql_fetch_assoc($results)) {
if ($i < 1) {
foreach($row as $key => $val) {
echo $key;//column name
}
}
//Do other stuff
$i++;
}
And yes, I know they should be doing mysqli_..., but this is my example using old mysql_...
Edit
To expand on this:
$query = "Select [stuff]";
$results = mysql_query($query);
$i = 0;
echo "<table>";
while ($row = mysql_fetch_assoc($results)) {
echo "<tr>";
if ($i < 1) {
foreach($row as $key => $val) {
echo "<td>".$key."</td>";//column name
}
}
echo "</tr>";
echo "<tr>";
foreach($row as $key => $val) {
echo "<td>".$val."</td>";//column name
}
echo "</tr>";
//Do other stuff
$i++;
}
You can use function mysql_list_fields for getting column names.
Code below gets data from sql. Including header column
// Data, depends on your sql statement
$sql_dt = array(); // make sure it is array
foreach( $sql_dt as $key => $val ) {
$data[] = <<< EOH
<tr>
<th>$val['column_name']</th> <tr/>
<th>$val['column_age']</th>
<tr/>
EOH;
}
$table_dt = implode( $data );
echo <<< EOT
<table>
<tr>
<th>Name</th> <tr/>
<th>Age</th>
<tr/>
{$table_dt}
<table/>
EOT;
<?php
//function to create a table
function makeTable($table, $columns){
$numFields = count($columns)-1;
$query = 'SELECT * FROM '.$table;
$result = mysql_query($query);
$arrayResult = mysql_fetch_array($result);
$num_rows = mysql_num_rows($result);
for ($x = 1; $x <= $num_rows; $x++){ //1st for loop
echo '<tr>';
for ($i = 0; $i <= $numFields; $i++){ //2nd for loop
echo '<td>'.$arrayResult[$columns[$i]].'</td>';
}
echo '</tr>';
}
}
?>
$columns is an array entered by the user eg: $columns = array ('Column1', 'Column2', 'Column3);. These are the names of the columns which are in a given $table.
My idea was to create a function that displays the data from the MySQL table with the info from the $columns array. The problem is in the second for loop. The value of $i is reset every time the first loop is done, so I get the same result over and over again (the number of rows in the table).
My question is this: How do I keep the $i in the second loop from resetting?
Thank you in advance.
The reason you get the same result over and over is not because $i, but $arrayResult.
The right way is like this:
//function to create a table
function makeTable($table, $columns){
$numFields = count($columns)-1;
$query = 'SELECT * FROM '.$table;
$result = mysql_query($query);
while ($arrayResult = mysql_fetch_array($result)){
echo '<tr>';
for ($i = 0; $i <= $numFields; $i++){ //2nd for loop
echo '<td>'.$arrayResult[$columns[$i]].'</td>';
}
echo '</tr>';
}
}
In your code you simple fetch always the first row and regardless of the subsequent cycles you only deal with that first row.
Just place
$arrayResult = mysql_fetch_array($result);
within the first loop just before echo '<tr>';
Anyway, for is not the best choice for iterating the records of a table, consider using while.
Why Dont you use while loop? If you use while you even don't need mysql_num_rows($result). Try this
function makeTable($table, $columns){
$numFields = count($columns)-1;
$query = 'SELECT * FROM '.$table;
$result = mysql_query($query);
while($arrayResult = mysql_fetch_array($result)){
echo '<tr>';
for ($i = 0; $i <= $numFields; $i++){ //2nd for loop
echo '<td>'.$arrayResult[$columns[$i]].'</td>';
}
echo '</tr>';
}
}
I m sure, you will get your ans
Your code won't work ever. Because you didn't read manual entry for mysql_fetch_array()
There is no use for the for loops these days. You need some manual to see how to deal with loops in PHP. foreach and while you will need more often than for.
The idea of creating such a function is wrong. combining SQL and HTML in one function is a sign of VERY BAD design. What you really need is a function to get SQL data into array and a template.
a function
function sqlArr($sql){
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
if ($res) {
while($row = mysql_fetch_array($res)){
$ret[] = $row;
}
}
return $ret;
}
a code
$data = sqlArr("SELECT * FROM table");
include 'template.php';
a template
<table border='1'>
<? foreach ($data as $row): ?>
<tr>
<? foreach ($row as $col): ?>
<td><?=$col?></td>
<? endforeach ?>
</tr>
<? endforeach ?>
</table>
However, you can put this latter template code into function, if you're gonna use it often.
and call it like
<? drawTable($data) ?>
I'm having a simple problem understanding how to parse stdObject returns from simple queries with mysqli ... I've tried a couple of different ways to turn the stdObject into an array and also just using fetch_object() like here:
$cart_q = "SELECT card_name FROM products WHERE product_cat = 'HPC' LIMIT 12";
$result = $mysqli->query($cart_q);
echo "<table>";
$i = 0;
while ($products = $result->fetch_object()) {
if($i == 0)
echo "<tr>";
echo "<td>". $products->card_name ."</td>";
$i++;
if($i == 3) {
echo "</tr>";
$i=0;
}
}
echo "<table>";
I've done a print_r of the object and gotten an associative array, but breaking it down to dislay within a page has yet to work ... any ideas?
Note: I actually think your problem is with iterating over the result array, thus label should be php, or /and HTML, but let's see:
Its usually good to separate retriving records from presentation, for example like this:
$mysqli = new MySQLi($db_host, $db_user, $db_pass, $db_name);
$cart_q = "SELECT card_name FROM products WHERE product_cat = 'HPC' LIMIT 12";
$result = $mysqli->query($cart_q) or die($mysqli->error);
$card_names = array();
while ( $row = $result->fetch_assoc() ){
$card_names[] = $row['card_name'];
}
Above will create array $card_names => array('card_name1', 'card_name2' ... etc)
Now, you can use foreach to iterate over that array and create output HTML. From what I've understood you want to create HTML table with 4 cells per row and one card name per cell.
echo '<table><tr>';
$i = 1;
foreach ( $card_names as $name ){
echo "<td>$name</td>";
if ( $i % 4 == 0) echo '</tr><tr>';
$i++;
}
($i - 1) % 4 == 0 ? echo '</tr></table>'; : echo '</table>';