check table from my sql query - php

Hello I'm checking duplicated data from tables. I have a problem that from where data selected. My code is:
$sub_cat = array();
$select = array("core_network","daisy_chain", "rf_bts", "rf_power", "rf_transmission");
$d='0';
for ($i=0;$i<=4;$i++){
$SQL = "SELECT sub_cat FROM (".$select[$i].") WHERE location=('".$id."')";
$result = mysql_query($SQL);
$cs=$d;
if ($result) {
while ($db_field = mysql_fetch_array($result)) {
if(!in_array($db_field['sub_cat'],$sub_cat)) {
$sub_cat[]= $db_field['sub_cat'];
$cs++;
$d=$cs;
$d--;
}
}
}
I need to know that sub_cat selected from which $select[i]. How to find it?

To get the values, do this:
$sub_cat = array();
$select = array("core_network","daisy_chain", "rf_bts", "rf_power", "rf_transmission");
$d='0';
for ($i=0;$i<=4;$i++){
$SQL = "SELECT sub_cat FROM (" . $select[$i] . ") WHERE location=('".$id."')";
$result = mysql_query($SQL); // deprecated - use PDO
$cs = $d;
if ($result) {
while ($db_field = mysql_fetch_array($result)) {
if(!in_array($db_field['sub_cat'], $sub_cat)) {
$table = $select[$i];
$sub_cat[$table][] = $db_field['sub_cat'];
// I have no clue what's going on here in your example:
$cs++;
$d=$cs;
$d--;
}
}
}
}
Then, to retrieve it:
foreach ($sub_cat as $table_name => $values) {
foreach ($values as $row) {
// output values here
}
}

Related

How do store a list of sorted tables with an SQL SHOW TABLES statement?

I am using the following code to show all tables, but how do I store the tables into a sorted array:
$sql = "SHOW TABLES FROM ".$counter_database." ORDER BY TABLES DESC";
$result = $conn->query($sql);
$outArray = array();
while($table = $result->fetch_assoc()) {
$outArrayx[] = $table;
}
The following code spits out the data:
foreach ($outArrayx as $key => $value) {
foreach ($value as $keys => $values) {
$sql = "SELECT * FROM ".$values." WHERE user_id='0'";
$result = $conn->query($sql);
if (strpos($values, "ckia") === 0) {
while($table = $result->fetch_assoc()) {
$outArray[] = $table;
}
}
}
}
Put the table names in a PHP array, and then sort the array. And if you don't nest it in the row, you don't need nested loops when you process it.
You can't use ORDER BY with SHOW TABLES, but you can use LIKE to select only tables that fit a pattern. Then you don't need the if statement in your loop.
$sql = "SHOW TABLES FROM ".$counter_database." LIKE 'ckia%'";
$result = $conn->query($sql);
$outArray = array();
while($table = $result->fetch_row()) {
$outArrayx[] = $table[0];
}
sort ($outArrayx);
foreach ($outArrayx as $table) {
$sql = "SELECT * FROM ".$table." WHERE user_id='0'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$outArray[] = $row;
}
}

Multiple Loops running together

$a_forms = array("a_GG", "a_FF");
$sql = "SELECT name, field FROM categories WHERE enabled = '1' ";
$result = mysqli_query($con,$sql);
$Others = array();
while($row = mysqli_fetch_array($result)) {
$Other_names[] = $row['name'];
$Other_fields[] = $row['db_field'];
}
for ($i=0;$i<count($a_forms);$i++) {
if ($a_forms[$i] == "a_FF") {
$dforms_sql = "SELECT *
FROM a_FF
where id=".$id;
$dforms_result = mysqli_query($con,$dforms_sql);
while ($forms_row = mysqli_fetch_array($dforms_result)) {
for ($i=0; $i<count($Other_fields); $i++) {
echo "<tr><td colspan='3'>".$Other_names[$i]."</td></tr>";
}
}
} elseif ($a_forms[$i] == "a_GG") {
$dforms_sql = "SELECT *
FROM a_GG where id=".$id;
$dforms_result = mysqli_query($con,$dforms_sql);
while($forms_row = mysqli_fetch_array($dforms_result)) {
echo 'Other cool stuff';
}
}
} //END (first) For Loop
So, for some reason, if that second for loop, $Other_field is there it will only show the IF statement for a_FF. But if the array = a_FF and a_GG and the for loop for $other_field is NOT there it displays them both. So it's obviously that for loop that is breaking something, I have no idea what though. Anyone have any thoughts?

Fetching record from two table and convert into json

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());
}

select query through function.. to fetch data from db

How do I fetch data from db using select query in a function?
Example
function ec_select_query($student, $row = '', $fields=array()) {
$qry = "SELECT * FROM student";
$qry = mysql_query($qry);
while($row = mysql_fetch_assoc($qry)){}
return $row;
}
If you want to return all rows then first save it in an array in while loop then return this array.
function ec_select_query($student,$row='',$fields=array())
{
$qry = "SELECT * FROM student";
$qry = mysql_query($qry);
$result = array();
while($row = mysql_fetch_assoc($qry))
{
$result[] = $row;
}
return $result;
}
Its is running code. Modify it according to your needs
$con = mysql_connect('localhost','root','') or die("Unable to connect to MySQL");
mysql_select_db('demo', $con) or die("Database not found");
function ec_select_query($student)
{
$query = "SELECT * FROM $student";
$result = mysql_query($query);
$row = array();
$getData = array();
while($row = mysql_fetch_array($result))
{
$getData[]=$row;
}
return $getData;
}
$information = ec_select_query('accountplans');
echo "<pre>"; print_r($information); die;
Try it
function select_query($table, $where=array(),$fields=array()){
$select_fields = $table."*";
if(!empty($fields) && is_array($fields)){
$select_fields = implode(",", $fields);
}
$sql = "select ".$select_fields." from ".$table." where 1=1 ";
if(!empty($where) && is_array($where)){
foreach ($where as $key => $value) {
$sql .= " AND ".$value;
}
}
$query = mysql_query($sql);
$result = array();
while($row = mysql_fetch_assoc($result)){
$result[] = $row;
}
return $result;
}
Call Function
$fields = array("id","name","city");
$where = array('name = "abc"','city like "aaa"');
$students = select_query("studendts", $where, $fields);
This code might help you :
function ec_select_query($student,$row='',$fields=array())
{
$q = "SELECT * FROM student";
$q = mysql_query($qry);
while($row = mysql_fetch_array($qry))
{
return $row;
}
}
It is easiest way to produce entire data in array
function db_set_recordset($sql) {
$qry = mysql_query($sql);
$row= array();
while($out = mysql_fetch_assoc($qry)) {
$row[] = $out;
}
return $row;
}
$qry = "SELECT * FROM student";
$result = db_set_recordset($qry);

Passing multiple dimension array in PHP

MySql query returns me a multi-dimensional array :
function d4g_get_contributions_info($profile_id)
{
$query = "select * from contributions where `project_id` = $profile_id";
$row = mysql_query($query) or die("Error getting profile information , Reason : " . mysql_error());
$contributions = array();
if(!mysql_num_rows($row)) echo "No Contributors";
while($fetched = mysql_fetch_array($row, MYSQL_ASSOC))
{
$contributions[$cnt]['user_id'] = $fetched['user_id'];
$contributions[$cnt]['ammount'] = $fetched['ammount'];
$contributions[$cnt]['date'] = $fetched['date'];
$cnt++;
}
return $contributions;
}
Now I need to print the values in the page where I had called this function. How do I do that ?
change the function like this:
while($fetched = mysql_fetch_array($row, MYSQL_ASSOC))
{
$contributions[] = array('user_id' => $fetched['user_id'],
'ammount' => $fetched['ammount'],
'date' => $fetched['date']);
}
return $contributions;
Then try below:
$profile_id = 1; // sample id
$result = d4g_get_contributions_info($profile_id);
foreach($result as $row){
$user_id = $row['user_id']
// Continue like this
}

Categories