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];
}
}
Related
I would like to import a single CSV with 7 columns into 2 tables in MySQL.
Columns 1, 2 and 3 go into a single row in table1. Columns 4 and 5 go as a row in table2. Columns 6 and 7 go as a row again in same table2.
How can this be done using PHP or mysql directly?
First fetch all values from csv and store it in an array. Then maintain your array as per your requirement and then start looping and inserting.
<?php
$efected = 0;
$file_temp = $_FILES["file"]["tmp_name"];
$handle = fopen($file_temp, "r"); // opening CSV file for reading
if ($handle) { // if file successfully opened
$i=0;
while (($CSVrecord = fgets($handle, 4096)) !== false) { // iterating through each line of our CSV
if($i>0)
{
list($name, $gender, $website, $category, $email, $subcat) = explode(',', $CSVrecord); // exploding CSV record (line) to the variables (fields)
//print_r($subcat); sub_cat_ids
if($email!='')
{
$chk_sql = "select * from employees where employee_email='".$email."'";
$chk_qry = mysqli_query($conn, $chk_sql);
$chk_num_row = mysqli_num_rows($chk_qry);
$cat_array = array(trim($category));
$subcat_array = explode( ';', $subcat );
if(count($subcat_array)>0)
{
$subcat_array_new = array();
foreach($subcat_array as $key => $val)
{
$subcat_array_new[] = trim($val);
}
}
$cat_sub_cat_merge = array_merge($cat_array, $subcat_array_new);
$cat_subcat_comma = implode( "','", $cat_sub_cat_merge );
foreach($cat_array as $cat_key => $cat_val)
{
$chk_cat_sql = "select * from employee_cats where cats_name = '".$cat_val."'";
$chk_cat_qry = mysqli_query($conn, $chk_cat_sql);
$chk_cat_num_row = mysqli_num_rows($chk_cat_qry);
//$all_cat_array = array();
if($chk_cat_num_row == 0)
{
$new_cat_ins = "insert into employee_cats set cats_name = '".$cat_val."', parent_cat_id = '0' ";
$new_cat_ins_qry = mysqli_query($conn, $new_cat_ins);
}
}
foreach($subcat_array_new as $subcat_key => $subcat_val)
{
$chk_subcat_sql = "select * from employee_cats where cats_name = '".$subcat_val."'";
$chk_subcat_qry = mysqli_query($conn, $chk_subcat_sql);
$chk_subcat_num_row = mysqli_num_rows($chk_subcat_qry);
//$all_cat_array = array();
if($chk_subcat_num_row == 0 && trim($subcat_val)!='')
{
//$category
$get_catid_sql = "select * from employee_cats where cats_name = '".trim($category)."'";
$chk_catid_qry = mysqli_query($conn, $get_catid_sql);
$fetch_cat_info = mysqli_fetch_array($chk_catid_qry);
$fetch_cat_id = $fetch_cat_info['cats_id'];
$new_subcat_ins = "insert into employee_cats set cats_name = '".$subcat_val."', parent_cat_id = '".$fetch_cat_id."' ";
$new_subcat_ins_qry = mysqli_query($conn, $new_subcat_ins);
}
}
$get_cat_sql = "select * from employee_cats where cats_name in ('".$cat_subcat_comma."')";
$get_cat_qry = mysqli_query($conn, $get_cat_sql);
$get_cat_num_row = mysqli_num_rows($get_cat_qry);
$sub_category_ids = array();
if($get_cat_num_row>0)
{
while($fetch_cat_id = mysqli_fetch_array($get_cat_qry))
{
if($fetch_cat_id['parent_cat_id']==0)
{
$category_id = $fetch_cat_id['cats_id'];
}
else
{
$sub_category_ids[] = $fetch_cat_id['cats_id'];
}
}
$sub_cat_id_vals_comma = implode(",", $sub_category_ids);
}
else
{
$category_id = 0;
$sub_cat_id_vals_comma = "";
}
if($chk_num_row>0)
{
// and here you can easily compose SQL queries and map you data to the tables you need using simple variables
$update_sql = "update employees set
employee_name='".$name."',
employee_gender='".$gender."',
employees_website='".$website."',
employees_cat_id='".$category_id."',
sub_cat_ids='".$sub_cat_id_vals_comma."'
where employee_email='".$email."'";
$mysqli_qry = mysqli_query($conn, $update_sql);
}
else
{
// and here you can easily compose SQL queries and map you data to the tables you need using simple variables
$insert_sql = "insert into employees set
employee_name='".$name."',
employee_gender='".$gender."',
employees_website='".$website."',
employees_cat_id='".$category_id."',
sub_cat_ids='".$sub_cat_id_vals_comma."',
employee_email='".$email."'";
$mysqli_qry = mysqli_query($conn, $insert_sql);
}
$efected = 1;
}
}
$i++;
}
fclose($handle); // closing file handler
}
if($efected==1)
{
header('location:'.$site_url.'?import=success');
}
else
{
header('location:'.$site_url.'?import=failed');
}
?>
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());
}
So, using the Latte engine I can't seem to loop through every data row in my table. I can only get the first one and I've run out of ideas!
$query = $this->db->query("SELECT id,title FROM table");
$array = array();
while($fetch = $query->fetch_assoc()) {
$array = $fetch;
}
$Template["listing"] = $array;
Template:
{foreach $listing as $item}
{$item["title"]}}
{/foreach}
Simpliest solution is (if you don't need $array variable elsewhere):
$query = $this->db->query("SELECT id,title FROM table");
while($fetch = $query->fetch_assoc()) {
$Template["listing"][] = $fetch;
}
Instead of $array = $fetch, run $array[] = $fetch, in order to add more items.
What you're doing is overwrite the array in every loop.
$query = $this->db->query("SELECT id,title FROM table");
$array = array();
while($fetch = $query->fetch_assoc()) {
$array[] = $fetch;
}
$Template["listing"] = $array;
$query = $this->db->query("SELECT id,title FROM table");
$array = array();
while($fetch = $query->fetch_assoc()) {
$array[] = $fetch;
}
$Template = $array;
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.
I am attempting to Dynamically update a MySql table, the $query looks correct when i echo it, but for some reason it dose not work when i insert the code into the MySql Query.
$b = 1;
$query_a = array();
$vars = array();
$result = mysql_query("SELECT * FROM my_table");
for ($i = 0; $i < mysql_num_fields($result); $i++) {
$vars[] = mysql_field_name($result,$b);
$b++;
}
foreach ($vars as $v)
{
if (isset($_GET[$v]))
{
$isclean = $_GET[$v];
$query[] = $v.' = '.$isclean.'';
}
}
$query = implode(',', $query);
mysql_query("UPDATE my_table SET $query WHERE UIN = '1'");
Without knowing your data types, my guess is it's because you're not adding single quotes around your values. You probably want something like:
$query[] = $v.' = \''.$isclean.'\'';