I am unsure how to display the items field. I want to display two tables of data; one that has all the items from a user and one with all the items to teh user. All I've been able to output is the item_id's(I pasted the html below). How to get all the item info from these ids, which is in the item table, and populate the HTML?
trans table
item table
$from = 1;
$sql = $db->prepare("SELECT * FROM test WHERE from_id = :id");
$sql->bindValue(':id', $from);
$sql->execute();
while($row = $sql->fetch())
{
$t =$row['items'];
$u =$row['to_id'];
$trans .= "<tr><th>Items</th><th>To</th><th>Status</th></tr><tr><td>$t</td>
<td>$u</td></tr>";
}
HTML DISPLAY
Try this!
<?php
$from = 1;
$sql = $db->prepare("SELECT * FROM test WHERE from_id = :id");
$sql->bindValue(':id', $from);
$sql->execute();
while($row = $sql->fetch())
{
$t =$row['items'];
$u =$row['to_id'];
$itemIDs = #explode(",", $t);
$items = array();
foreach($itemIDs as $ID){
$sqlItem = $db->prepare("SELECT itemname FROM itemtable WHERE itemid = :itemid");
$sqlItem->bindValue(':itemid', $ID);
$sqlItem->execute();
$itemname ='';
while($rowItems = $sqlItem->fetch())
{
$itemname .=$rowItems['itemname'];
}
$items[$t] = $itemname;
}
$trans .= "<tr><th>Items</th><th>To</th><th>Status</th></tr><tr><td>$items[$t]</td> <td>$u</td></tr>";
}
below is my code for testing,
<?php
$from = 1;
$sql = mysqli_query($db,"SELECT * FROM test WHERE from_id = '$from'");
while($row = mysqli_fetch_array($sql))
{
$t =$row['items'];
$u =$row['to_id'];
$itemIDs = #explode(",", $t);
$itemname ='';
foreach($itemIDs as $ID){
$sqlItem = mysqli_query($db, "SELECT itemname FROM itemtable WHERE item_id = '$ID'");
while($rowItems = mysqli_fetch_array($sqlItem))
{
$itemname .= $rowItems['itemname'].', ';
}
$items[$u] = $itemname;
}
$trans .= "<tr><th>Items</th><th>To</th><th>Status</th></tr><tr><td>$items[$u]</td> <td>$u</td></tr>";
}
echo "<table>".$trans."</table>";
?>
Note : change my queries with ur need
in ur while loop
while($row = $sql->fetch())
{
$items_array = array();
$items_array = explode(",",$row["items"]);
foreach($items_array as $key => $value)
{
//modify ur query according to ur need
$query3 = "SELECT item_name
FROM item_table
WHERE item_id =".$value." ";
$result3 = mysql_query($query3);
$row3 = mysql_fetch_assoc($result3);
$item_name .= $row3['subcategory_name'].", ";
}
}
now ur array will contains item_id,
use foreach loop in ur while loop and get info of Item from item table with item_id from expolode function
Within while you will have to fire new query that will get the information of items.
For eg :
"SELECT * FROM item_info_table WHERE id IN (id1,id2, id3)"
It will return you the item information corresponding to the id's.
The data is not normalized. Get it to normalize and you'll have a much better and cleaner solution.
Related
Hi I'm new in PHP and trying to get the below response using php sql but i'm not be able to find the such desire output
[{"Id":1, "name": "India", "Cities":[{"Id":1, "Name":"Mumbai", "country_id":1}, {"Id":2,"Name":"Delhi","country_id":1},
"id":3,"Name":Banglore","country_id":1}, {"Id":2, "Name":"USA", "Cities":[{"Id":6, "Name":"New York", "country_id":2},.....
I have two tables one is country based and other is city based.
I tried
<?php
include_once("config.inc.php");
$sql = "SELECT * FROM country";
$sqlCity = "SELECT * FROM city";
$cityQuery = mysqli_query($conn, $sqlCity);
$sqlQuery = mysqli_query($conn, $sql);
$mainArray = array();
if(mysqli_num_rows($cityQuery) > 0 ){
$cityResponse = array();
while($resCity = mysqli_fetch_assoc($cityQuery)){
$cityResponse[] = $resCity;
}
if(mysqli_num_rows($sqlQuery) > 0 ){
$response = array();
while($res = mysqli_fetch_assoc($sqlQuery)){
$response[] = $res;
}
foreach($cityResponse as $city){
foreach($response as $country){
if($city['country_id'] == $country['id']){
$mainArray = array("Cities" => $city);
}
}
}
echo '{"response": '.json_encode($response).', '.json_encode($mainArray).' "success": true}';
}
}else{
echo '{"response": '.json_encode($response).' "success": false}';
}
?>
currently my response showing
{"response": [{"id":"1","name":"India"},{"id":"2","name":"USA"},{"id":"3","name":"UK"}], {"Cities":{"id":"15","name":"Manchester","country_id":"3"}} "success": true}
For detail code explanation check the inline comments
Modify the SQL query with related column names
The memory you have to take care. By default memory limit in php is 128MB in 5.3
Check the code and let me know the result
<?php
$data = array();
//include your database configuration files
include_once("config.inc.php");
//execute the join query to fetch the result
$sql = "SELECT country.country_id, country.name AS country_name,".
" city.city_id, city.name AS city_name FROM country ".
" JOIN city ON city.country_id=country.country_id ".
" ORDER BY country.country_id ";
//execute query
$sqlQuery = mysqli_query($conn, $sql) or die('error exists on select query');
//check the number of rows count
if(mysqli_num_rows($sqlQuery) > 0 ){
//country id temprory array
$country_id = array();
//loop each result
while($result = mysqli_fetch_assoc($sqlQuery)){
//check the country id is already exist the only push the city entries
if(!in_array($result['country_id'],$country_id)) {
//if the city is for new country then add it to the main container
if(isset($entry) && !empty($entry)) {
array_push($data, $entry);
}
//create entry array
$entry = array();
$entry['Id'] = $result['country_id'];
$entry['name'] = $result['country_name'];
$entry['Cities'] = array();
//create cities array
$city = array();
$city['Id'] = $result['city_id'];
$city['name'] = $result['city_name'];
$city['country_id'] = $result['country_id'];
//append city entry
array_push($entry['Cities'], $city);
$country_id[] = $result['country_id'];
}
else {
//create and append city entry only
$city = array();
$city['Id'] = $result['city_id'];
$city['name'] = $result['city_name'];
$city['country_id'] = $result['country_id'];
array_push($entry['Cities'], $city);
}
}
}
//display and check the expected results
echo json_encode($data);
use like this
<?php
include_once("config.inc.php");
$sql = "SELECT * FROM country";
$sqlCity = "SELECT * FROM city";
$cityQuery = mysqli_query($conn, $sqlCity);
$sqlQuery = mysqli_query($conn, $sql);
$mainArray = array();
if(mysqli_num_rows($cityQuery) > 0 ){
$cityResponse = array();
while($resCity = mysqli_fetch_assoc($cityQuery)){
$cityResponse[] = $resCity;
}
if(mysqli_num_rows($sqlQuery) > 0 ){
$response = array();
while($res = mysqli_fetch_assoc($sqlQuery)){
$response[] = $res;
}
foreach($cityResponse as $city){
foreach($response as $country){
if($city['country_id'] == $country['id']){
$mainArray = array("Cities" => $city);
}
}
}
echo json_encode(array('result'=>'true','Cities'=>$mainArray));
}
}else{
echo json_encode(array('result'=>'false','Cities'=>$response));
}
?>
You can use try this. It actually works for me and it's cool. You can extend to 3 or more tables by editing the code.
try {
$results = array();
$query = "SELECT * FROM country";
$values = array();
$stmt = $datab->prepare($query);
$stmt->execute($values);
while($country = $stmt->fetch(PDO::FETCH_ASSOC)){
$cities = null;
$query2 = "SELECT * FROM city WHERE country_id = ?" ;
$values2 = array($country['id']);
$stmt2 = $datab->prepare($query2);
$stmt2->execute($values2);
$cities = $stmt2->fetchAll();
if($cities){
$country['cities'] = $cities;
} else {
$country['cities'] = '';
}
array_push($results, $country);
}
echo json_encode(array("Countries" => $results));
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
I'm having a hard time getting this search results with pagination code to work. It does successfully grab the search keyword entered in the html form on another page and brings it into this search.php page. if I echo $search I see the keyword on the page. But I get no results even though I should for the query. Can anyone see what might be going on?
require "PDO_Pagination.php";
if(isset($_REQUEST["search_text"]) && $_REQUEST["search_text"] != "")
{
$search = htmlspecialchars($_REQUEST["search_text"]);
$pagination->param = "&search=$search";
echo $search;
$pagination->rowCount("SELECT * FROM stories WHERE stories.genre = $search");
$pagination->config(3, 5);
$sql = "SELECT * FROM stories WHERE stories.genre = $search ORDER BY SID ASC LIMIT $pagination->start_row, $pagination->max_rows";
$query = $connection->prepare($sql);
$query->execute();
$model = array();
while($rows = $query->fetch())
{
$model[] = $rows;
}
}
else
{
$pagination->rowCount("SELECT * FROM stories");
$pagination->config(3, 5);
$sql = "SELECT * FROM stories ORDER BY SID ASC LIMIT $pagination->start_row, $pagination->max_rows";
$query = $connection->prepare($sql);
$query->execute();
$model = array();
while($rows = $query->fetch())
{
$model[] = $rows;
}
}
$query = "SELECT * FROM stories";
if(isset($_REQUEST["search_text"]) && $_REQUEST["search_text"] != "")
{
$search = htmlspecialchars($_REQUEST["search_text"]);
$pagination->param = "&search=$search";
$query .= " WHERE genre LIKE '%$search%'";
}
// No need for else statement.
$pagination->rowCount($query);
$pagination->config(3, 5);
$query .= " ORDER BY SID ASC LIMIT {$pagination->start_row}, {$pagination->max_rows}";
$stmt = $connection->prepare($query);
$stmt->execute();
$model = $stmt->fetchAll();
var_dump($model);
In your query do:
WHERE stories.genre LIKE '%string%');
instead of:
WHERE stories.genre = 'string');
Because the equals will want to literally equal the field.
Following is my PHP code which is only giving i =0 though in a loop I am incrementing the $i but it always return i as 0 and while loop is only working one time, though my query SELECT * FROM events WHERE DATE(event_date) < CURDATE() is returning 7 records when exectuing in phpmyadmin. Let me know what i am doing wrong here ?
Code -
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/app/'."config.php";
error_reporting(E_ALL);
if( $_POST['number'] == 'all' ) {
$eventArr = array();
$myarray = array();
$query = "SELECT * FROM events WHERE DATE(`event_date`) < CURDATE()";
$result = mysql_query($query);
$i =0;
while($row = mysql_fetch_assoc($result)) {
$eventArr[$i] = array('event_data'=> $row);
// Get image For an event
$event_id = $row['id'];
$query = "SELECT * FROM event_images WHERE event_id = $event_id ORDER BY `uploaded_date` DESC LIMIT 0,1";
$result = mysql_query($query);
$eventImgArr = array();
while($row = mysql_fetch_assoc($result)) {
$eventImgArr[] = $row;
}
$eventArr[$i]['event_image'] = $eventImgArr;
// Get venue details for the event
$venue_id = $row['venue_id'];
$eventVenArr = array();
$query = "SELECT * FROM `venues` WHERE id = $venue_id";
while($row = mysql_fetch_assoc($result)) {
$eventVenArr[] = $row;
}
$eventArr[$i]['venue_detail'] = $eventVenArr;
echo $i, " -- ";
$i++;
}
$myarray = array('response'=>'1','message'=>'Event data', 'data'=>$eventArr);
echo json_encode($myarray);
return;
}
You are re-using the $result variable for the other queries, which is destroying its value needed for the main loop.
P.S. Also, you're not actually executing the query for the venue details.
I need an SQL query that displays all the records if its duplicated also. For instance say
select * from table where true and p_id in(1,2,1,1)
displays only records from 1 and 2 but i need it to be repeated when given in while loop.
Update with code:
$cook = unserialize($_COOKIE["pro_cook"]);
foreach ($cook as $something) {
$merc[] = $something;
}
foreach ($size as $new_size) {
$size_array[] = $new_size;
}
$items = count($merc);
$mer = rtrim(implode(',', array_reverse($merc)), ',');
$fulclr = "and p_id in (".$mer.")";
$asd = "(p_id,".$mer.")";
$result = mysql_query("select * from product_details where true ".$fulclr." order by field".$asd."");
Hope this will help
$ids = "1,2,1,1";
$sql = "select * from table where true and p_id in (".$ids.")";
$rec = mysql_query($sql);
$dbData = array();
while($res = mysql_fetch_assoc($rec)) {
$dbData[$res['p_id']] = $res;
}
$ids = explode(',', $ids);
$newArray = array();
foreach ($ids as $id) {
if (!empty($dbData[$id])) {
$newArray[] = $dbData[$id];
}
}
Hi I would like to display the number of item in the database. The following is the php code:
$jobid = $_SESSION['SESS_MEMBER_JOB'];
$data = "SELECT * FROM attributes WHERE jobid = $jobid";
$attribid = mysql_query($data) or die(mysql_error);
$count = "SELECT count(*) FROM attributes WHERE jobid = $jobid";
$database_count = mysql_query($count);
//Declare the Array
$DuetiesDesc = array();
print_r ($database_count);
But instead of getting the desired result, I get :
Resource id #14
Please Assist
Should get it out of the way that you shouldn't be using mysql_* see Why shouldn't I use mysql_* functions in PHP?
See the code below... explanations are in comments
$jobid = $_SESSION['SESS_MEMBER_JOB'];
// escape variables using mysql_real_escape_string
$data = "SELECT * FROM attributes WHERE jobid =".mysql_real_escape_string($jobid);
$attrRes = mysql_query($data) or die(mysql_error());
// I'm assuming you want all of the attributes return in this query in an array
$attributes = array();
while($row = mysql_fetch_assoc($attrRes)){
$attributes[] = $row;
}
// Now if you want the count we have all of the records in the attributes array;
$numAttributes = count($attributes);
// here is an example of how you can iterate through it..
print "<p>Found ".$numAttributes." attributes</p>";
print "<table>";
foreach($attributes as $row){
print "<tr>";
foreach ($row as $cell){
print "<td>".$cell."</td>";
}
print "</tr>";
}
print "</table>";
Try this
<?php
$jobid = $_SESSION['SESS_MEMBER_JOB'];
$data = "SELECT * FROM attributes WHERE jobid =$jobid";
$attribid = mysql_query($data) or die(mysql_error);
$count=mysql_num_rows($attribid);
echo $count;
?>
try this
$jobid = $_SESSION['SESS_MEMBER_JOB'];
$data = "SELECT *FROM attributes WHERE jobid =$jobid";
$attribid = mysql_query($data) or die(mysql_error);
$count = "SELECT count(*) FROM attributes WHERE jobid = $jobid";
$database_count = mysql_query($count);
//Declare the Array
$DuetiesDesc = array();
$database_count=mysql_fetch_assoc($database_count);
echo $database_count['count(*)'];