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.
Related
I'm trying to match results from this PHP code into this Bootstrap HTML structure.
What I'm able to achieve so far is printing items from database in 3-column layout, but I don't known how to combine this results with/ info my bootstrap html "structure/ table". I think I need to work with "id" and increment it after every "echo" (h4)? But I'm very new to PHP. Thank you for any practical advices.
PHP CODE:
// Run query on connection
$query = "SELECT
product.id,
product.name as product_name,
product.price,
product.type
FROM pizza_project.product
INNER JOIN pizza_project.product_type on product.type = product_type.id
where product.type in (1,2)
order by product.type ASC, product.price ASC";
$result = $con->query($query);
?>
<table>
<tr>
<?php
$split = 0;
$id = $row['id']; // just an idea I think I need to start with
if (mysqli_num_rows($result) > 0) {
foreach ($result as $row) {
echo '<td>' . $row['product_name'] . ' ' . $row['id'] . '</td>';
$split++;
if ($split%3 == 0) {
echo '</tr> </tr>';
}
}
}
?>
</tr>
</table>
<?php
$itemsInRow = 0;
foreach ($result as $row) {
if ($itemsInRow === 0)
echo "<div class=\"row text-center\">";
echo "<div class=\"col-md-4\">";
echo "<span class=\"fa-stack fa-4x\">";
echo "<img class=\"product-image\" src=\"" . $row['img'] . "\">";
echo "</span>";
echo "<h4 class=\"service-heading\">" . $row['headline'] . "</h4>";
echo "<p class=\"text-muted\">" . $row['text'] . "</p>";
echo "</div>";
if ($itemsInRow === 0)
echo "</div>";
if ($itemsInRow % 3 === 0) {
$itemsInRow = 0;
continue;
}
$itemsInRow++;
}
Is this what you are trying to achieve? I will improve my answers if its the right way. This is not tested.
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);
I've been throw so many threads for 4+ hours here and abroad and seem to be missing a simple thing.
I'm trying to have several users upload their 'news' to MYSQL.
Yet I want to display only the 'news' with the logged in username (userpost) attached to the row.
$current is the username for who is logged in, which works.
Example A isn't filtering out rows that don't contain the $current user.
Example B isn't providing any output
So I've tried both A:
$result = mysqli_query($con,"SELECT * FROM images_tbl");
//echo $current . "2" . $current;
while($row = mysqli_fetch_array($result)) {
if ($row['userpost'] = '.$current.') {
$num = 0;
$num = $num + 1;
$pic.$num = $row['images_path'];
$h1 = $row['hlone'];
and B:
$result = mysqli_query($con,"SELECT * FROM images_tbl WHERE (userpost = '.$current.')");
echo $current . "2" . $current;
while($row = mysqli_fetch_array($result)) {
echo $row['hlone'] . " " . $row['images_path'];
echo "<img src=\"" .$row['images_path']. "\">";
}
27, images/08-10-2014-1412752801.jpg(images_path), 2014-10-08, Headline(hlone), Headline2, story, testb(userpost)
Any help would be greatly appreciated.
Add where clause to your query
//in situation A
$result = mysqli_query($con,"SELECT * FROM images_tbl where username='".$current."'");
//username is column name for user you might have to change this
while($row = mysqli_fetch_array($result)) {
echo $row['images_path'];
echo $row['hlone'];
}
In situation B try this
$result = mysqli_query($con,"SELECT * FROM images_tbl WHERE userpost = '".$current."')");
echo $current . "2" . $current;
while($row = mysqli_fetch_array($result)) {
echo $row['hlone'] . " " . $row['images_path'];
echo "<img src=\"" .$row['images_path']. "\">";
}
Why are you trying to filter with PHP.
If you want to filter the 'news' that have not written by current user just use MySQL Where clause:
// For Example A
$result = mysqli_query($con, "SELECT * FROM images_tbl WHERE userpost != '{$current}'");
while($row = mysqli_fetch_array($result)) {
$pic = $row['images_path'];
$h1 = $row['hlone'];
}
// For Example B
$result = mysqli_query($con,"SELECT * FROM images_tbl WHERE userpost = '{$current}')");
echo $current . "2" . $current;
while($row = mysqli_fetch_array($result)) {
echo $row['hlone'] . " " . $row['images_path'];
echo "<img src=\"" .$row['images_path']. "\">";
}
It's easy with MySQL's filtering options. You should do more research about MySQL.
How i separate the first result of for each loop and remaining. I have 2 divs, i want first result to be displayed there and rest on another div.
Also is there any way that i can get json decode without for each loop, i want to display result based on for each values from database, and querying database in for each loop is not recommended.
Here is my code, What i want
<div class="FirstDiv">
Result1
</div>
<div class="RemDiv">
Remaining result from for each loop
</div>
Here is full code
$data = json_decode($response->raw_body, true);
$i = 0;
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
if (++$i == 6)
break;
$check = "SELECT fullname FROM test_celebrities WHERE shortname = '$value[prediction]'";
$rs = mysqli_query($con,$check);
if (mysqli_num_rows($rs)==1) //uid found in the table
{
$row = mysqli_fetch_assoc($rs);
$fullname= $row['fullname'];
}
echo 'Celebrity Name: ' . $fullname . '<br/>';
echo 'Similar: ' . $value['confidence']*100 .'%'. '<br/><br/>';
echo "<img src='actors/$value[prediction].jpg'>";
echo "<hr/>";
}
Try this:
$data = json_decode($response->raw_body, true);
$i = 0;
echo '<div class="FirstDiv">'; // add this line here
foreach( $data['photos'][0]['tags'][0]['uids'] as $value ) {
if (++$i == 6) break;
$check = "SELECT fullname FROM test_celebrities WHERE shortname = '$value[prediction]'";
$rs = mysqli_query($con,$check);
if ( mysqli_num_rows($rs) == 1 ) { //uid found in the table
$row = mysqli_fetch_assoc($rs);
$fullname= $row['fullname'];
}
// Echo celebrity information:
echo 'Celebrity Name: ' . $fullname . '<br/>';
echo 'Similar: ' . $value['confidence']*100 .'%'. '<br/><br/>';
echo "<img src='actors/$value[prediction].jpg'>";
echo "<hr/>";
if ($i==1) { echo '</div><div class="RemDiv">'; }; // add this line here
}
echo '</div>'; // close the last tag
$predictions=array();
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
$predictions[]="'" . mysqli_real_escape_string($con, $value[prediction]) . "'";
}
$check="SELECT fullname FROM test_celebrities WHERE shortname IN (" . implode(',' $predictions) . ")";
$rs = mysqli_query($con,$check);
while ($row = mysqli_fetch_assoc($rs)) {
if (!$count++) {
// this is the first row
}
But note that you now have two sets of data which are sorted differently - hence you'll need to iterate through one and lookup values in the other.
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;
}