I'm trying to retrieve records from the mySQL-database but nothing gets selected. I'm using the below php function:
function printButton($conn){
$your_variable = 1;
$knappar = $conn->prepare('SELECT * FROM knappar WHERE pid < :parameter');
$knappar->bindParam(':parameter', $your_variable, PDO::PARAM_INT);
$knappar->execute();
//Loops boxes
$count = 1;
while ($row = $knappar->fetch(PDO::FETCH_ASSOC)) {
echo "<a href='#'><div class='box' id='div_item".$count."'>";
echo $row['header'];
echo $row['id'];
echo "</div></a>";
$count = $count + 1;
}
}
It works fine if I change "WHERE pid = 1" instead of the "< :parameter". What am I doing wrong?
I updated it to what it looks like now:
function printButton($conn){
$your_variable = 1;
$knappar = $conn->prepare('SELECT header FROM knappar WHERE pid < :parameter');
$knappar->bindParam(':parameter', $your_variable, PDO::PARAM_INT);
$knappar->execute();
//Loops boxes
$results = $knappar -> fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $row){
echo $row['header'];
echo '<br />';
}
}
With above example, still no output. pid value is int(11) in the database and the value of all rows are 1.
$knappar -> fetch(PDO::FETCH_ASSOC) only fetches the next row of the result set. Use fetchAll to get the entire result set.
You could then iterate through the returned array with a foreach.
Granted, I'm not sure why it returns nothing rather than just the first row but give it a try.
Related
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!
I am trying to run a query off multiple array variables and display the results in a table.
The user selects 1 or more records, which includes BOL and CONTAINER. These selections are put in their own arrays and they are always an equal amount.
<?php
$bolArray = explode(',', $_POST['BOL']);
$containerArray = explode(',', $_POST['CONTAINER']);
$count = count($bolArray); // to get the total amount in the arrays
I use a FOR loop to separate each value from the 2 arrays:
for($i = 0; $i < $count; $i++)
{
$bol = $bolArray[$i];
$container = $containerArray[$i];
}
Here is the part where I'm stuck and probably where I am messing up.
I need to take each variable from the FOR loop and run query using both variables.
First, I'll start the table:
echo "<table><thead><tr><th>BOL</th><th>Container</th></thead><tbody>";
Here is where I tried a FOREACH loop:
foreach($containerArray as $container) // I am not sure if I am using this FOREACH correctly
{
And now, the query. Please take note of the variables from the first FOR loop:
$preQuery = "SELECT * FROM mainTable WHERE CONTAINER = '".$container."' AND BOL = '".$bol."'";
$preRes = mysql_query($preQuery) or die(mysql_error());
$preNum = mysql_num_rows($preRes);
I use a WHILE loop with a mysql_fetch_assoc:
while($preRow = mysql_fetch_assoc($preRes))
{
echo '<tr>'
echo '<td>'.$preRow[BOL_NUMBER].'</td>';
echo '<td>'.$preRow[CONTAINER_NUMBER].'</td>';
echo '<td>'.$preRow[ANOTHER_COLUMN].'</td>';
echo '</tr>'
}
}
echo '</tbody></table>';
?>
The query actually works. Problem is, it only returns 1 record, and it's always the last record. The user could select 4 records, but only the last record is returned in the table.
I tried to use the same query and paste it inside the first FOR loop. I echoed out the query and it displayed the same amount of times as the number of array values, but will only return data for the last record.
I do not understand what I am doing wrong. I just want to display data for each value from the array.
Edit
Here is what the code looks like when I throw the query in the first FOR loop:
echo "<table class='table table-bordered'><thead><tr><th>BOL</th><th>Container</th></tr></thead><tbody>";
for($i = 0; $i < $count; $i++)
{
$bol = $bolArray[$i];
$container = $containerArray[$i];
$preQuery = "SELECT BOL_NUMBER, CONTAINER_NUMBER FROM `intermodal_main_view` WHERE BOL_NUMBER = '". $bol ."' AND CONTAINER_NUMBER = '".$container."'";
$preRes = mysql_query($preQuery) or die();
$preNum = mysql_num_rows($preRes);
while($preRow = mysql_fetch_assoc($preRes))
{
echo '<tr>';
echo '<td>'.$preRow[BOL_NUMBER].'</td>';
echo '<td>'.$preRow[CONTAINER_NUMBER].'</td>';
echo '</tr>';
}
}
echo "</tbody></table>";
I think you can use "IN" if your POST vars are comma separated.
$preQuery = "
SELECT * FROM mainTable
WHERE CONTAINER IN ($_POST['CONTAINER'])
AND BOL IN ($_POST['BOL'])
";
$preRes = mysql_query($preQuery) or die(mysql_error());
$preNum = mysql_num_rows($preRes);
Then go to your while loop....
This would omit the need for creating an array and looping it.
Also, you need to switch to PDO for your query, and switch to parameter binding. It will take all of an hour to learn.
I am trying to pass id to second page which I am selecting from another table but the below code isn't working. When I do var_dump I can see that the values are what I want but the rows for main query don't show up(The title and image aren't being displayed).
I have two queries in which the one is inside the other one. Can someone help me out? The main query works fine if I get rid of the while loop of the second query.
$paginate = new pagination($page, "SELECT * FROM table1 where title != '' ORDER BY id desc" , $options);
}
}
catch(paginationException $e)
{
echo $e;
exit();
}
if($paginate->success == true)
{
$result = $paginate->resultset->fetchAll();
foreach($result as $row)
{
$dx = $row['image_one'];//image_one from main query
//second query
$item = $mydb->prepare("select * from table2 where imageone = ?");
$item->bind_param('s', $dx);
$item->execute();
$item_res = $item->get_result();
while($row = $item_res->fetch_assoc()){
$rx = $row['id'];
var_dump($rx);
} //the rows below aren't being displayed
$path = 'images/';
echo "<a href='second.php?title=".urlencode($row['title'])." &item=".$row['id']."&id=".$rx."'>"."<img src='".$path."".$row['image_one']."'/></div>"."</a>";
}
Try this:
echo "<a href='second.php?title="'.urlencode($row['title']).'" &item="'.$row['id'].'"&id="'.$rx.'"'>"."<img src='"'.$path.'"".$row['image_one']."'/></div>"."</a>";
use ' ' around var name
You are reassigning $row in your while loop once it exits $row is null.
Try this instead:
while($item_row = $item_res->fetch_assoc()) {
$rx = $item_row['id'];
}
Also, instead of nested queries you should try using a join.
Currently, $selection outputs the following: MIN(Bale_ID), MIN(Incoming_Moisture) which is exactly what it should be outputting (they're names from another table). However, when I put $selection into the mysql_query $data1, it seems to just be reading the last value (MIN(Incoming_Moisture)) and only displays the results for that. How do I get the query to read the entire array of elements in $selection? Thank you!!
while ($row1 = mysql_fetch_array($fieldnames1)) {
$fields = $row1['fields1'];
$explode = explode(',',$fields);
if ($row1) {
for ($i=0; $i<$minrows; $i++) {
if ($i<$minrows-1){
$comma = ", ";
}
else {
$comma = "";
}
//$selection = "MIN(".$explode[$i].")".$comma;
//echo $selection;
$data1 = mysql_query("SELECT MIN(".$explode[$i].")".$comma." from data WHERE (fchmitimestamp LIKE CONCAT(#year,'%',#month,'%',#day,'_________'))");
$all1 = mysql_num_fields($data1); //return # of columns; for some reason is returning "1" right now.
while ($row2 = mysql_fetch_array($data1)) {
for ($col=0; $col<$all1; $col++) {
echo $all1;
echo "<td>Min: " . $row2[$col] . "</td>";
}
echo "</tr>";
}
}
}
}
echo "</table>";
Look at the order of operations in your code:
loop {
... fetch data ...
... assign results to $data1 ...
}
Nowhere in your loop do you output or save the results you've got in $data1, so each iteration of the loop overwrites the results of the previous iteration - in other words, only the LAST iteration's results will be stored.
you are running the query once per for loop cycle (1 field at a time) and since first ones yields in SQL error because of the trailin comma, these will not be echoed except the last one.
-- notice the error in first query
SELECT MIN(Bale_ID), from data WHERE (fchmitimestamp LIKE CONCAT(#year,'%',#month,'%',#day,'_________'))
SELECT MIN(Incoming_Moisture) from data WHERE (fchmitimestamp LIKE CONCAT(#year,'%',#month,'%',#day,'_________'))
use var_dump($selection) instead of echo $selection to see yourself
Here is what I would like to do; I am passing an encoded data as a query variable to my webpage, then in my php page, I am decoding the data and checking the same in my database. The code I am using is shown below:
<?php
// Get the ID from URL.
$id = ( isset($_GET["id"]) && !empty($_GET["id"]) ? $_GET["id"] : "");
// If "id" is not empty, proceed.
if(!empty($id)) {
$id = base64_decode($id);
global $wpdb;
$res = $wpdb->query("SELECT * FROM S_redirect WHERE source = ".$id);
$tot = count($res);
echo $tot . " records found.";
for( $i=0; $i<count($res); $i++) {
echo $res[$i]->id;
}
exit;
}
else {
echo "No ID";
exit;
}
?>
I have one record in my database. The above code correctly says "1 records found". I am not sure how to get the value of the field in that row. I have 3 columns, they are id, field1 and field2. The code "echo $res[$i]->id" returns nothing.
Please help
BTW, I am trying this in my Wordpress blog.
Thank you all for your suggestions. I tried your suggestions and here are my results:
$res = $wpdb->query("SELECT * FROM S_redirect WHERE source = ".$id);
$tot = count($res);
echo $tot . " records found."."</br>";
it says 1 records found.
$res = $wpdb->get_row("SELECT * FROM S_redirect WHERE source = ".$id);
$tot = count($res);
echo $tot . " records found."."</br>";
it says 0 records found.
$res = $wpdb->get_results("SELECT * FROM S_redirect WHERE source = ".$id);
$tot = count($res);
echo $tot . " records found."."</br>";
it says 0 records found.
while ($row = mysql_fetch_array($res)) {
echo $row[0];
}
If I use mysql_fetch_array,
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/myfolder/mytheme/index.php on line 38.
line 38 is while ($row = mysql_fetch_array($res)) {.
What I am trying to accomplish:
I have a wordpress blog. All the above code goes into my index.php. I will pass a product id to my index.php via query string variable. I have created a new table called S_redirect in my wordpress database. I will retrieve the value of query string variable id and check the same in my database table. If record exists, then retrieve one of the column value (url of the product) from that table row and redirect to that product url. If the record doesn't exists then redirect to home page. hope this helps everyone to understand what I am doing.
Judging by $wpdb, it looks like this is a WordPress. Hopefully this will help:
http://codex.wordpress.org/Function_Reference/wpdb_Class
Update
Don't use count() to get the number of rows; use $wpdb->num_rows (no () because it's a property, not a function). The count() function always returns 1 for any non-null value that it doesn't recognize as a "countable" value (i.e., arrays and certain objects), so it's likely your code will always yield 1.
$tot = $wpdb->num_rows;
=====
If you run your query with get_results() instead of query(), then you can loop through the results like this:
foreach ($res as $row) {
echo $row->id;
}
Ultimately, I think your code will end up looking like this:
$res = $wpdb->get_results("SELECT * FROM S_redirect WHERE source = ".$id);
$tot = $wpdb->num_rows;
echo $tot . " records found.";
foreach ($res as $row) {
echo $row->id;
}
Disclaimer: This is untested, as I've never used WordPress. This is just how I understand it from the documentation linked above. Hopefully it at least gets you on the right track.
Use:
$tot = count(mysql_fetch_array($res));
or
$tot = mysql_num_rows($res);
The best is
while($row = mysql_fetch_assoc($res)){
echo $row['column_name'];
}