fetch PDO::FETCH_ASSOC multiple checkboxes - php

usually i help people with whatever they need, this time i'm asking for your help.
i'm trying to get a specific row from my database after preforming multiple checkbox select i spend 50 hours on that and i couldn't manage to do that.
each time i'm changing something in my code i get a different ERROR.
i was looking for an answer in every HTML page that exist on the INTERNET !
please show me the light..
here is a part of my form.... value means "size" of the toy
<div class=""><input type="checkbox" name="toys[]" value="6X2" /><label></label></div>
<div class=""><input type="checkbox" name="toys[]" value="4X3" /><label></label></div>
<div class=""><input type="checkbox" name="toys[]" value="8X2.5" /><label></label></div></strike>
here is the PHP code...
if (isset($_POST['toys'])) {
foreach($_POST['toys'] as $each_check) {
}
}
$query = $db->query = 'SELECT * FROM `toys` WHERE SIZE = '.$each_check;
echo "<table>";
echo "<tr>
<th>ratio</th>
<th>size</th>
<th>built</th>
<th>description</th>
</tr>";
while ($row = $query->fetch(PDO::FETCH_ASSOC))
echo "<tr><td>" . $row['ratio'] .
"</td><td>" . $row['size'] .
"</td><td>" . $row['built'] .
"</td><td>" . $row['description'] .
"</td></tr>";
echo "</table>";

This is so very far from being valid:
if (isset($_POST['toys'])) {
foreach($_POST['toys'] as $each_check) {
}
}
$query = $db->query = 'SELECT * FROM `toys` WHERE SIZE = '.$each_check;
More like:
if (isset($_POST['toys'])) {
foreach($_POST['toys'] as $each_check) {
$query = $db->query("SELECT * FROM `toys` WHERE SIZE = '".$each_check."'");
}
}
But should be more like:
if (isset($_POST['toys'])) {
$query = 'SELECT * FROM `toys` WHERE SIZE = ?';
$sth = $db->prepare($query);
foreach($_POST['toys'] as $each_check) {
if( ! $sth->execute(array($each_check)) ) {
die('MySQL Error: ' . var_export($sth->error_info(), TRUE);
}
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
// code here
}
}
}

You're assigning $db->query instead of using it as a function. Change your query line to this:
$query = $db->prepare('SELECT * FROM `toys` WHERE SIZE = :size');
$query->bindValue(':size',$each_check);
$query->execute();
Also, you're going through $_POST['toys'], but not assigning it to any value. I'm guessing you want to add all of your query and table code within the foreach.
if (isset($_POST['toys'])) {
foreach($_POST['toys'] as $each_check) {
// put everything else here
}
}

I want to suggest that you use MySQL's IN (...) clause in your WHERE condition to retrieve all the rows with matching 'size' in just 1 query:
SELECT * FROM toys WHERE size IN ( $chosenSizes )
To get the list of sizes, use PHP's implode function:
$chosenSizes = implode(', ', $_POST['toys']);
You can then use PDO's fetchAll to fetch all rows into a result array.
$resultRows = $sth->fetchAll();
Note: Only use this method when you are quite certain that the result arrays is not too big!

Hagay, the following should work for you:
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'my_name', 'my_pass');
if (isset($_POST['toys'])) {
$sizes = implode(', ', array_map(array($pdo, 'quote'), $_POST['toys']));
$sql = "SELECT * FROM toys WHERE size IN (" . $sizes . ")";
echo '<table>', PHP_EOL;
echo '<tr><th>ratio</th><th>size</th></tr>', PHP_EOL;
foreach( $pdo->query($sql) as $row ) {
echo '<tr><td>', $row['ratio'], '</td><td?', $row['size'], '</td></tr>', PHP_EOL;
}
echo '</table>', PHP_EOL;
}

Related

Issue with duplicate data in array and SQL

I have this function that reads the contents of an array, and outputs data form a mysql database into a table. However, when there are duplicated in the array, it only lists that information once. In the code below, it will only give me three table rows, 1, 100 and 140. It skips over the second instance of 1. How would I fix that to output the data into the table regardless of there being duplicates?
$con = mysql_connect('localhost', 'root', 'password');
$table = "cwr";
$player1pod1 = array(1, 1, 100, 140);
function generatelistplayer1 ($player1pod1, $con, $table){
$sql = "SELECT * FROM $table WHERE id IN (".implode(',',$player1pod1).")";
$myData = mysql_query($sql, $con);
echo "<table border='1' cellpadding='2'> ";
while($row = mysql_fetch_array( $myData )) {
echo "<tr>";
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['cardname'] . '</td>';
echo '<td>' . $row['rarity'] . '</td>';
}
echo "</table>";
Desired output for the table is :
1
1
100
140
I'm getting :
1
100
140
It's only going to give you 3 rows, because it's only going to give you unique rows. You can instead use a UNION query if you want actual duplicates.
"SELECT * FROM $table WHERE id = 1 UNION ALL SELECT * FROM $table WHERE id IN (".implode(',',$player1pod1).")";
If you want to use the array, you can create a loop:
$query = [];
foreach($player1pod1 as $pod) {
$query[] = "SELECT * FROM $table WHERE id = $pod";
}
$sql = implode(" UNION ALL ",$query);
Fetch all the results first (into an array, key is the id), then based on your original list, display each result.
You can print the result as many times as you need in a loop.
Notice its not a loop on the query. Query to db will be done only once, and I do not recommend a solution which do multiple queries or query same data more than once.
If order is not important i.e array(1, 100, 1, 140) = is good as = array(1, 1, 100, 140) , we can use array_count_values($player1pod1) and print each result as much as needed:
$con = mysql_connect('localhost', 'root', 'password');
$table = "cwr";
$player1pod1 = array(1, 1, 100, 140);
function generatelistplayer1 ($player1pod1, $con, $table)
{
$counts = array_count_values($player1pod1);
$sql = "SELECT * FROM $table WHERE id IN (" . implode(',', $player1pod1) . ")";
$myData = mysql_query($sql, $con);
echo "<table border='1' cellpadding='2'> ";
while ($row = mysql_fetch_array($myData)) {
for ($i=0;$i<count($counts[$row['id']]);$i++) {
echo "<tr>";
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['cardname'] . '</td>';
echo '<td>' . $row['rarity'] . '</td>';
}
}
echo "</table>";
}
In case that the order is do important we can first collect data from the databse sql, and then to print it one by one, with "print_rows" function in my example. In this solution we don't need to count the values but we use some RAM to hold the sql results:
function generatelistplayer1 ($player1pod1, $con, $table)
{
$sql = "SELECT * FROM $table WHERE id IN (" . implode(',', $player1pod1) . ")";
$myData = mysql_query($sql, $con);
//extract data
$sql_data = array();
while ($row = mysql_fetch_array($myData)) {
$sql_data[$row['id']] = array( 'cardname'=> $row['cardname'],'rarity'=> $row['rarity']);
}
//print data
print_rows($player1pod1,$sql_data);
}
function print_rows($player1pod1, $mysql_data)
{
echo "<table border='1' cellpadding='2'> ";
for($i=0;$i<count($player1pod1);$i++) {
echo "<tr>";
echo '<td>' . $player1pod1[$i] . '</td>';
echo '<td>' . $mysql_data[$player1pod1[$i]['cardname']] . '</td>';
echo '<td>' . $mysql_data[$player1pod1[$i]['rarity']] . '</td>';
}
echo "</table>";
}

PHP and mysqli to modify CSS

I was experimenting if I could use a mySQL database to store CSS settings. I set up a simple database "colors" with one table "color" that had simple structure tag and color columns. In that, one row is h1 => red.
<?php
//function to dynamically change CSS
$tag = 'h1';
$q = "SELECT * FROM `colors` WHERE `tag`='" . $tag . "'" ;
echo $q . "<br>";
$query = mysqli_query($link, $q);
if ($row = mysqli_fetch_assoc($query))
{
echo $row['color'];
} else
{
echo "error - no such tag";
}
?>
When I tried to convert to a function, the code does not work at all.
<?php
//function to dynamically change CSS
function getCSS($tag)
{
$tag = 'h1';
$q = "SELECT * FROM `colors` WHERE `tag`='" . $tag . "'" ;
echo $q . "<br>";
$query = mysqli_query($link, $q);
if ($row = mysqli_fetch_assoc($query))
{
echo $row['color'];
} else
{
echo "error - no such tag";
}
}
getCSS('h1');
?>
Help please?
My guess is that in
$query = mysqli_query($link, $q);
$link goes out of scope and is empty. You should pass it to the function as well.
For the record: using $tag without escaping could be an sql injection attack possibility.
in function, there is no $link, you shoud define it as a global variable.
At the start of your function add a reference to your global DB link:
function getCSS($tag) {
global $link;
...
This should work:
<?php
$link = mysqli_connect('server_host', 'user', 'password', 'database') OR die('Could not connect because: '.mysqli_connect_error());
//function to dynamically change CSS
function getCSS($link, $tag){
$q = 'SELECT * FROM colors WHERE tag = "' . $tag . '"' ;
$r = mysqli_query($link, $q);
if(mysqli_num_rows($r)>0){ // check if there are results
while($row = mysqli_fetch_assoc($r)){
//echo '<pre>';
//print_r($row); // print the result array for debugging
//echo '</pre>';
echo $row['color'] . '<br />';
}
return $row;
} else { // if no result is found
echo 'No such tag';
}
}
// test it:
echo '<br />if tag is h1<br />';
getCSS($link, 'h1');
echo '<br />if tag is h2<br />';
getCSS($link, 'h2');
?>

Query not running

I wonder if anyone can spot what is going wrong here? The first query has been tested and is working because I can print out the $groups array, but the 2nd one will not run. When I hard code the $groups array it runs fine.
require ('mysqli_connect.php'); // Connect to the db.
echo '<p>If no record is shown, this is because you had an incorrect or missing entry in the search form.<br>Click the back button on the browser and try again</p>';
//Coming from another page
$uninum=$_POST['uninum'];
$sname=$_POST['sname'];
$groups = array ( );
$count = count ($groups);
$q1 = "SELECT `groupid` FROM `groups`
WHERE `uninum` = '".$uninum."'";
$result1 = #mysqli_query($dbcon,$q1);
while ($row1 = mysqli_fetch_array ($result1, MYSQLI_ASSOC)){
$groups[] = $row1['groupid'];
}
for ($i = 0; $i < $count; $i++){
$q = "SELECT participants.sname, participants.uninum,
groups.groupid
FROM participants
INNER JOIN groups ON
participants.uninum = groups.uninum
WHERE groups.groupid ='".$groups[$i]."'";
$result = #mysqli_query ($dbcon, $q); // Run the query.
if ($result) { // If it ran, display the records.
// Table header.
echo '<table>
<tr>
<td><b>Edit</b></td>
<td><b>Surnname</b></td>
<td><b>University ID</b></td>
<td><b>Group</b></td>
</tr>';
// Fetch and display the records:
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo '<tr>
<td>Edit</td>
<td>' . $row['sname'] . '</td>
<td>' . $row['uninum'] . '</td>
<td>' . $row['groupid'] . '</td>
</tr>';
}
echo '</table>'; // Close the table.
mysqli_free_result ($result); // Free up the resources.
echo "<br><br>";
} else { // If it did not run OK.
// Public message:
echo '<p class="error">The current users could not be retrieved. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbcon) . '<br><br>Query: ' . $q . '</p>';
}
}
$groups = array ( );
$count = count ($groups);
$count is always equal zero
Try removing # with mysqli_query also $groups array will not start looping until your count is greater then zero.
if you var_dump($count) it will return zero.
$count = count ($groups);
var_dump($count);
You should count array after the query returns result set, right after ending while loop
$q1 = "SELECT `groupid` FROM `groups` WHERE `uninum` = '".$uninum."'";
$result1 = #mysqli_query($dbcon,$q1);
while ($row1 = mysqli_fetch_array ($result1, MYSQLI_ASSOC)){
$groups[] = $row1['groupid'];
}
// count here
$count = count ($groups);

PHP select field from nested query

I am running a query on 2 tables, to return information from a blog. The nested query selects the tags that are associated with that blog, which is a separate table.
I want to be able to get the 'tag' row from the 'tags' table and display these on the page. My code is below and I have commented where I would like the rows to be selected.
<?php
include("inc/dbconnection.php");
$id = $_GET['tag'];
$id = trim($id);
$result = mysqli_query($conn, "
SELECT *
FROM blog
WHERE blog_id IN (SELECT blog_id FROM tags WHERE tag = '$id')
");
if (!$result) {
die("Database query failed: " . mysqli_error($conn));
} //!$result
else {
$rows = mysqli_num_rows($result);
if ($rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$content = $row['content'];
$content2 = substr($content, 0, 100);
/* Below is where I would like to pull the row 'tag' from the nested query */
$rawTag = $row['tag'];
$tag = str_replace(" ", "", $rawTag);
$tagArray = explode(",", $tag);
$tag = "";
for ($i = 0; $i < count($tagArray); $i++) {
$tag .= "<a href='tag-" . $tagArray[$i] . ".php'>" . $tagArray[$i] . "</a> ";
} //$i = 0; $i < count($tagArray); $i++
echo "
<table>
<tr>
<th>
<a href='blog-" . $row['blog_id'] . ".php'>
<h2>" . $row['title'] . "</h2>
</a>
</th>
</tr>
<tr>
<td>
<p>" . date("d/m/Y", strtotime($row['createdDate'])) . "</p><br />
<span>" . $content2 . "...</span><br />
<span><small>Tags: " . $tag . "</small></span>
</td>
</tr>
</table>";
} //$row = mysqli_fetch_array($result, MYSQLi_ASSOC)
} //$rows > 0
else { //$rows > 0
echo "<br /><h1>There are currently no blogs with the selected tag (" . $_GET['tag'] . ")</h1><br /><h2>Please check back later.</h2>";
}
}
?>
Sorry if this is a stupid question and thanks in advance for your help :)
There are two part one is Query and second is data display.So Data display is total based
on your business call (how to display tag data in HTML.. )
but here you can optimize first part
(query for fetching data) as below:
$result = mysqli_query($conn, "SELECT b.*, t.* FROM blog b inner join tags t on
b.blog_id= t.blog_id WHERE t.blog_id '" . $id . "')");
Please use this.

Need help displaying mysql database contents to webpage

I need help displaying data from mysql to a webpage, I am coding in php.
My database consists of products which are cars(same type e.g Chevy), right now I have 2 rows (I can add more if I want to), each cars contains the image path, and description.
I can show one row (car) but I am unable to show all rows. I know I have to go through a loop to get all the data from the cars database but I am not sure how to implement it.
This is what I have so far. Assuming I already connected to my database
note: the image path I would like to show the picture in my website.
This is how i would like it to display in my webpage:
$query = "SELECT * FROM cars where cars.carType = 'Chevy' AND \
cars.active = 1";
$numberOfFieds = mysqli_num_fields($result);
$numberOfRows = mysqli_num_rows($result);
/* Gets the contents */
$row = mysqli_fetch_row($result);
$rows = mysqli_fetch_assoc($result);
$fieldcarssontable = array_keys($row);
echo "<table>";
while($row = mysqli_fetch_assoc($result)){
echo "<th>" . $fieldcarssontable[imgPath] . "</th>";
echo "<th>" . $fieldcarssontable[description] . "</th>";
}
echo "</tr>";
echo "</table>";
Just add a while loop. mysqli_fetch_assoc returns a row and moves the internal pointer to the next row until all rows are fetched, then it returns false and the while loop will stop
Pseudo syntax to understand while
while ( this is true ) {
execute this
}
So on your case you can say
while ( $row = mysqli_fetch_assoc( $result ) ) {
// process/output $row
}
mysqli_fetch_assoc and mysqli_fetch_row literally do the same, assoc gives you the array with your result field names as index so this is simpler to access ( $row['name'] rather than $row[0] when using fetch_row )
Have fun! :)
EDIT
// connect to your database server
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
// an error occured
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
// build your query
$query = "SELECT
* # select actual fields instead of *
FROM
cars
WHERE
cars.carType = 'Chevy'
AND
cars.active = 1";
// execute query
$result = mysqli_query($link, $query );
if ( !$result ) {
die( 'no result' );
}
// number of fields
$numberOfFields = mysqli_num_fields($result);
// the field names
$fieldNames = mysqli_fetch_fields($result);
// number of result rows
$numberOfRows = mysqli_num_rows($result);
// watch the content of fieldName and compare it with the table header in the output
print_r( $fieldName );
echo "<table>\n";
// table header, not neccessary to put this into a loop if the query isn't dynamic
// so you actually know your field names - you can echo the header without any variable.
// for the sake of learning about loops I added this
foreach( $fieldNames as $index => $fieldName ) {
echo "\t<th>field #" $index . ", name:" . $fieldName . "</th>\n";
}
// now it's time to walk through your result rows, since we only need to check for "true" a while loop does best
while ( $row = mysqli_fetch_assoc( $result ) ) {
echo "\t<tr><td>" . $row['imgPath'] . "</td><td>" . $row['description'] . "</td></tr>\n";
}
echo "</table>\n";
// remove the result from memory
mysqli_free_result( $result );
mysqli_close( $link );
You misspelled $numberOfFields in your loop, which means you're using a different variable for your loop control. Your loop won't work.
I recommend turning on the error reporting so PHP can catch this stuff for you.
Use this... just while loop
<?php
// Array
while($result = mysql_fetch_assoc($result)) {
//show you fields
echo $result["FieldName"];
}
?>
Or use this proper
<?php
// Edit it as per your query
$query = "SELECT * FROM cars";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while($row = $result->fetch_assoc()) {
//show you fields
echo $row["Name"];
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();
?>

Categories