mysqli returns simple query as object - why? - php

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

Related

PHP / MySQL - how to transpose data (columns into rows) with dynamic column names into a table

I know there are other questions/answers about this sort of thing, but it took me a while to figure this specifically out, so I figured I'd share it with the community, as likely there are others who could benefit.
I had put together code like the following, which worked fine, but if you needed to add a column, meant adding the name 4 times before you even got to adding it where you wanted in the table:
<?php
// Prepare statement & retreive data from database
$sql_retreive = $con->prepare("
SELECT widget_id
, widget_name
, widget_price
, widget_upc
, widget_color
FROM widgets
WHERE widget_price > ?
");
$bind_process = $sql_retreive->bind_param('d',$price);
$sql_retreive->execute();
$result = $sql_retreive->get_result();
// Initiate arrays to place variables from query in order to transpose data from database
$widget_id = [];
$widget_name = [];
$widget_price = [];
$widget_upc = [];
$widget_color = [];
// If there are results, fetch values for each row and add values to each corresponding array
if($result->num_rows > 0 ){
while($row=$result->fetch_assoc()){
$widget_id[] = $row['widget_id'];
$widget_name[] = $row['widget_name'];
$widget_price[] = $row['widget_price'];
$widget_upc[] = $row['widget_upc'];
$widget_color[] = $row['widget_color'];
} // end of while
} // end of if num_rows > 0
// Build dynamic table with results transposed
echo "<table class='table'><thead>";
echo "<tr><th>Widgets</th>"; for ($i=0; $i<count($crop_name);$i++) {echo "<th>".$widget_name[$i]." (".$widget_id[$i].")</th>";}
echo "</tr></thead><tbody>";
echo "<tr><td>widget_price</td>"; for ($i=0; $i<count($widget_price);$i++) {echo "<td>".$widget_price[$i]."</td>";} echo "</tr>";
echo "<tr><td>widget_upc</td>"; for ($i=0; $i<count($widget_upc);$i++) {echo "<td>".$widget_upc[$i]."</td>";} echo "</tr>";
echo "<tr><td>widget_color</td>"; for ($i=0; $i<count($widget_color);$i++) {echo "<td>".$widget_color[$i]."</td>";} echo "</tr>";
echo "</tbody></table>";
?>
So I wanted to figure out a better way... see my answer below...
After spending a while working on it, I came up with this:
<?php
// Prepare statement & retreive data from database
$sql_retreive = $con->prepare("SELECT widget_id, widget_name, widget_price, widget_upc, widget_color FROM widgets WHERE widget_price > ?");
$bind_process = $sql_retreive->bind_param('d',$price);
$sql_retreive->execute();
$result = $sql_retreive->get_result();
if($result->num_rows > 0 ){ // If there are results, fetch values for each row and add values to each corresponding array
// Initiate an array for each field specified, in which to place variables from query, in order to transpose data from database
for($i = 0; $i < mysqli_num_fields($result); $i++) { // loop through fields
$field_info = mysqli_fetch_field($result); // for each, retreive the field info
$column = $field_info->name; // retreive the field name from the field info
$$column = []; // note double $$, create a blank array using the field name, will loop through for each
} // end of for loop
while($row=$result->fetch_assoc()){ // for each row of responses, place the data into the above created arrays
$field_info = mysqli_fetch_fields($result); // retreive the field info
foreach ($field_info as $field_value) { // for each, retreive the field info
$column = $field_value->name; // retreive the field name from the field info
$$column[] = $row[$column]; // note double $$, using the array (which uses the field name), place the row data in, and loop through for each
} // end of foreach loop
} // end of while
} // end of if num_rows > 0
// Build dynamic table with results transposed
echo "<table class='table'><thead>";
echo "<tr><th>Widgets</th>"; for ($i=0; $i<count($crop_name);$i++) {echo "<th>".$widget_name[$i]." (".$widget_id[$i].")</th>";}
echo "</tr></thead><tbody>";
echo "<tr><td>widget_price</td>"; for ($i=0; $i<count($widget_price);$i++) {echo "<td>".$widget_price[$i]."</td>";} echo "</tr>";
echo "<tr><td>widget_upc</td>"; for ($i=0; $i<count($widget_upc);$i++) {echo "<td>".$widget_upc[$i]."</td>";} echo "</tr>";
echo "<tr><td>widget_color</td>"; for ($i=0; $i<count($widget_color);$i++) {echo "<td>".$widget_color[$i]."</td>";} echo "</tr>";
echo "</tbody></table>";
?>
This enables you to just add the column/field name into the query, and then use the values where you want in the table.
Please upvote if you find this helpful!

output entire table of oracle DB in website with php and save as CSV

I am stuck at tryping to output an Oracle table with PHP on my website.
I can only output the row information in one line at the moment, other things fail and do not give me back anything or a parse error.
What I have:
<?php
set_time_limit(0);
$conn = oci_connect("name", "pw", "localhost/service_name");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['Error occured - no conenction created']), E_USER_ERROR);
$sql = 'SELECT * FROM VIEW_DFINVENTORY
WHERE ARTTIV NOT LIKE :didbv
AND ROWNUM <= 100
ORDER BY ARTID';
$stid = oci_parse($conn, $sql);
$didbv = 1;
oci_bind_by_name($stid, ':didbv', $didbv);
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_ASSOC)) != false) {
echo $row['ARTID'] ."<br>\n";
echo $row['ARTCODE'] ."<br>\n";
This only gives me back the information like this:
ARTID
ARTCODE
ARTID
ARTCODE
ARTID
ARTCODE
...
the output with data:
13546987400
1234
1658198200R
1324
874312346AR
8792
...
How can I output the entire table/view as it is for example shown in SQLdeveloper or by outputting it to CSV with SQLPlus with all its headers and rows?
I looked around and found a loop that puts out in my case only a blank page on the browser:
<?php
set_time_limit(0);
$conn = oci_connect("name", "pw", "localhost/service_name");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['Error occured - no conenction created']), E_USER_ERROR);
$sql = 'SELECT * FROM VIEW_DFINVENTORY
WHERE ARTTIV NOT LIKE :didbv
AND ROWNUM <= 100
ORDER BY ARTID';
$stid = oci_parse($conn, $sql);
$didbv = 1;
oci_bind_by_name($stid, ':didbv', $didbv);
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_ASSOC)) != false) {
$results = array();
foreach($results as $row)
{
echo "<tr>\n";
foreach($row as $index=>$value)
{
echo "<td>$value</td>\n";
}
echo "</tr>\n";
}
oci_free_statement($stid);
oci_close($conn);
?>
I am new to PHP so is there something I missed? I am really stuck and trying to fix this since over 12 hours now. Some sources are too advanced for me. Maybe you know a good tutorial for this. Every approach is welcomed.
I highly appreciate your help.
Thank you already in advance,
Matt
I'll use the second code example and add comments so you can see what actually happens :)
<?php
//...
/* oci_fetch_array returns you one row for the executed SQL-statement
* in each loop run $row contains one row/line of the table.
* $row always contains all selected columns (in your case * = all columns) of VIEW_DFINVENTORY
*/
while (($row = oci_fetch_array($stid, OCI_ASSOC)) != false) {
echo "<tr>";
//you can now print out all relevant columns of one line (if you know the column name)
//or automatically all columns you have selected
foreach ($row as $columnName => $columnValue){
//print one data column
echo "<td>".$columnValue."</td>";
}
echo "</tr>";
}
Sometimes you maybe want the first row of the table containing all the column Names (=table header) then you should add this code before the while-loop
$columnsCount = oci_num_fields($stid);
echo "<tr>";
for ($i = 1; $i <= $columnsCount ; $i++) {
$colname = oci_field_name($stid, $i);
echo " <th>".htmlspecialchars($colname,ENT_QUOTES|ENT_SUBSTITUTE)."</th>";
}
echo "</tr>";

Split mySQL Query Results using PHP

I am working on a PHP function that looks up the list of departments in a school stored in a database table using MySQL and then splits the results into two columns if the result is more than 1 department.
I have tried for, while and foreach loops and for some reason I keep getting an endless loop as a result. I am not sure where I am going wrong.
My function is as follows:
function translateDegreeLists($school) {
require('includes/EM-langSelect-4.php');
$values = array();
$coacs_code = 1;
$cob_code = 2;
$avcon_code = 4;
$coe_code = 3;
$cose_code = 5;
$cotm_code = 6;
$query = "SELECT dept_name, ".$content." AS content FROM explore_majors.departments WHERE school_id = ".$school."";
$result = mysql_query($query);
$nums = mysql_num_rows($result);
if($nums == 1) {
echo '1 Option';
}
elseif(($nums / 2) == 2) {
echo '2 Columns with 2 Options';
}
elseif (($nums / 2) >= 3) {
echo '2 Columns with more than 3 Options';
}
echo '<div class="column column-1-2">';
for ($i=0; $i < $nums; $i++)
{
$row = mysql_fetch_assoc($result);
$dept_name = $row['content'];
echo '<h4>'.$dept_name.'</h4>';
echo '<ul>';
echo '<li>test</li>';
echo '</ul>';
}
echo '</div>';
}
Note: The $content in the query is pulled from the EM-lang-4.php which determines the browser language and selects the appropriate column in the DB.
This is the base of the function as the code above generates a list of 4 departments all within the same column div.
The end result is that I want the function to calculate how many departments are found and if more than 1, split them equally between 2 divs. The divs will be identical with the exception of the content inside.
Any ideas what I am doing wrong?
I believe the problem is that you are running mysql_fetch_assoc every time in the for loop. The loop should be structured as so:
while ($row = mysql_fetch_assoc($result)) {
$dept_name = $row['content'];
echo '<h4>'.$dept_name.'</h4>';
echo '<ul>';
echo '<li>test</li>';
echo '</ul>';
}
Note that this will not format the columns but you will at least be able to print the results of your query.
Php.net is your friend! See example one in the documentation for mysql_fetch_assoc
Lastly mysql_*** functions are deprecated and will eventually be removed from future php versions! See the red warning in the docs

Fetch all fields from all rows - MYSQL

I understand this could appear alarming but bear with me.
I need to echo every field in every row in a table.
This is only an example - I have removed the HTML wrapped around it to improve readability.
$a = 1;
while ($a <= $count_rows) {
$query = "SELECT col1, col2 etc.. FROM table WHERE `id`='$id'";
$result = mysqli_query($con, $query);
$i = 1;
while($i <= $count_fields) {
$row = mysqli_fetch_array($result, MYSQL_NUM);
echo "$row[$i]";
$i++;
}
$a++;
$id = $a;
}
This only outputs the first field of every row? Why?
If I echo $row[2] I get nothing!
If I echo $row[2] I get nothing!
because it's actually third item
and there is some strange code interfering with $i variable
Anyway, to get every column from every row ou need a code like this
$query = "SELECT * FROM table";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_row($result)) {
foreach ($row as $index => $value) {
echo "$index => $value, ";
}
echo "<br>\n";
}

PHP MySQL data FOR loop

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

Categories