I want to throw multiple json from this page so that I an fetch json file to show the output for my mobile application with java programming. Following is my code which displays proper json from table "news" however, I want to throw json of other object available in my database. Is that possible?
$dblink = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
mysqli_query($dblink, 'SET NAMES utf8');
//Check connection was successful
if ($dblink->connect_errno) {
printf("Failed to connect to database");
exit();
}
$result = $dblink->query("SELECT * FROM news ORDER BY id DESC");
$dbdata = array();
while ( $row = $result->fetch_assoc()) {
$dbdata[]=$row;
}
echo json_encode($dbdata);
?>
It's up to you how you combine them, it could be as simple as:
Merge:
$dbdata = array_merge($dbdata1, $dbdata2);
echo json_encode(dbdata);
Different Keys:
$dbdata = array(
'table_1' => $dbdata1,
'table_2' => $dbdata2
);
echo json_encode($dbdata);
MySQL Join:
SELECT n.*, m.* FROM news n LEFT JOIN news_meta m ON m.news_id = n.news_id ORDER BY n.id DESC;
/* $dbdata will then contain your two tables worth of data: */
echo json_encode($dbdata);
Related
I have table named category which contain names of other tables in the same database. I want to fetch table names from category table and then fetch data from each table from db. So far I have this code below:
$db = new mysqli('localhost', 'root', '', 'db_cat');
if($db){
// $q = "SELECT TABLE";
// $echo = $db->query($q);
// echo $echo;
// $result = $db->query("SHOW TABLES");
$qCat="SELECT * FROM product_category";
$cat_query= $db->query($qCat) or die(mysql_error());
while ($fetch= $cat_query->fetch_object())
{
$cat_id=$fetch->id;
$category=$fetch->category;
$p_cat=str_replace(" ","_",strtolower($category).'_categories');
//if(strlen($category)>22){$fine_product_name= substr($service, 0,19).'...';}else{ $fine_product_name=$category;}
$result = $db->query("SHOW TABLES");
while($row = $result->fetch_array()){
$tables[] = $row[0];
}
}
The second query must be different.
$result = $db->query("SELECT * FROM $category");
while($row = $result->fetch_array()){
$tables[] = $row[0];
}
print_r($tables);
First of all your design to connect to a database is not that good, Please check the below code for a proper way of connecting to it.
<?php
$con=mysqli_connect("localhost","root","","db_cat");
//servername,username,password,dbname
if (mysqli_connect_errno())
{
echo "Failed to connect to MySql: ".mysqli_connect_error();
}
?>
Here is a sample code of getting data from a table ( where this table name is in another table).
$get_table_name ="SELECT TableName FROM table_name";
$get_name=mysqli_query($con,$get_table_name);
$count=0;
while($row_name=mysqli_fetch_array($get_name)){
$count++;
$tbName=$row_name['TableName'];
$_SESSION['table_name'][count]=$tbName;
}
This will show you how to fetch data from one table. You can use a For loop to get all the tables
$table=$_SESSION['table_name'][1];
$get_table ="SELECT * FROM $table";
.... // Normal way of fetching data
You can try to adjust your code according to this and improve it.
For further reference please refer http://php.net/manual/en/book.mysqli.php
Going by the advice that join are better than nested queries, I've converted all my nested queries to join. However, upon converting to join, I'm unable to retrieve data into my array from the SQL result.
Here are my queries :
Without join
$a="SELECT F_DATE, COUNT(F_DATE) as COUNT_F
from FWH
where FI_NAME IN
(
SELECT I_NAME from INS_W WHERE INSTANCE_ID IN
(
SELECT I_MAP_ID FROM T_MAP where T_MAP_ID =
(
SELECT T_ID FROM TWY WHERE T_NAME = 'abc'
)
)
)
AND F_DATE between '$S_D' AND '$E_D'
GROUP BY F_DATE";
With join
$a="SELECT t1.F_DATE AS DATE_F, COUNT(t1.F_DATE) as COUNT_F
from FWH t1
JOIN INS_W t2 ON(t1.FI_NAME = t2.I_NAME)
JOIN T_MAP t3 ON(t2.INSTANCE_ID = t3.I_MAP_ID)
JOIN TWY t4 ON(t3.T_MAP_ID = t4.T_ID)
WHERE t4.T_NAME = 'abc' AND
t1.F_DATE BETWEEN '$S_D' AND 'E_D'GROUP BY t1.F_DATE";
Here's the PHP code to retrieve data
$link = mysql_connect("ip", "user", "passs");
$dbcheck = mysql_select_db("db");
if ($dbcheck) {
$chart_array_1[] = "['F DATE','F COUNT']";
$result = mysql_query($a);
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$f_date=$row["DATE_F"];
$f_count=$row["COUNT_F"];
$chart_array_1[]="['".$f_date."',".$f_count."]";
}
}
}
mysqli_close($link);
The SQL queries themselves run fine when tested directly on MySQL DB.
For some reason, when I use joins, I'm forced to use row[0], row[1] etc instead of fetching values using the name of column. I do not understand the reason behind this. However, this is the only way out in my case. Code below for those who may get stuck in a similar situation as me.
$link = mysql_connect("ip", "user", "passs");
$dbcheck = mysql_select_db("db");
if ($dbcheck) {
$chart_array_1[] = "['F DATE','F COUNT']";
$result = mysql_query($a);
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$chart_array_1[]="['".$row[0]."',".$row[1]."]";
}
}
}
mysqli_close($link);
So I am trying something totally new (for me). I have a PHP file where I try to retrieve the data of 2 tables and replace values if they match. Since I'm not really sure what I'm doing I'm kinda stuck:) Here is what i want:
I have 2 tables in my mysql database.
The table 'advertisement' has the column 'logo_fid'.
The table 'files' has the columns 'fid' and 'filepath'.
Now I would like to echo the values of the 'logo_fid' column in the 'advertisement' table.
Before that, however, I would like to see if in the table 'files' a corresponding value is stored in the 'fid' volumn and if so I would like to echo the value of 'filepath' instead of the value of 'logo_fid'.
So basically what I want is to replace the returned value of the logo_fid column, if this value matches with the value in the 'fid' column, with the corresponding 'filepath' value.
Hope I made myself clear. Anyway I have this code atm. Hope that anybody can help me out with this one. Thanks a lot!
<?php
//connection info xxxx
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//advertisement SELECT
$sql = "SELECT logo_fid FROM advertisement ORDER BY nid ASC";
$result = $conn->query($sql);
//advertisement SELECT
$sql2 = "SELECT fid, filepath FROM files";
$result2 = $conn->query($sql2);
if ($result->num_rows > 0 && $result2->num_rows > 0) {
// output data of each row
while(($row = $result->fetch_assoc()) && ($row2 = $result2->fetch_assoc())){
//So after i received all the info i'd like to check if the value of logo_fid matches with fid and if so replace the value with the value of filepath
if ($row["logo_fid"] == $row2["fid"]) :
echo $row2["filepath"];
else :
echo $row["logo_fid"];
endif;
echo '<br>';
}
} else {
echo "0 results";
}
$conn->close();
?>
Seems like this could be done as one query.
SELECT A.logo_Fid, F.Fid, F.filePath, coalesce(F.FilePath, Logo_Fid) as ValueYouWant
FROM advertisement A
LEFT JOIN files F
on A.logo_Fid = F.FID
Then you can echo ValueYouWant without the inline logic.
The join relates the two tables on the Fid and logo_fid.
if a match is found, Valueyouwant will contain the f.filepath, if no match is found logo_fid will be in valueyouwant.
Since this is using a LEFT join, all values from advertisement will be returned, and only related records from files will be returned.
so to display...
I don't do much PHP, but an online search that was accpted as an answer indicates it would be something like this...
$sql=" SELECT A.logo_Fid, F.Fid, F.filePath, coalesce(F.FilePath, Logo_Fid) as ValueYouWant
FROM advertisement A
LEFT JOIN files F
on A.logo_Fid = F.FID ORDER BY NID asc"
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo $row['ValueYouWant'];
echo '<br>';
}
I am trying to retrieve data from 2 tables in the same database (mySQL). I have tried to use an INNER JOIN but I have realised that the WHERE used to SELECT entries is not the same on both tables i.e.. id on properties is not the same as id on reports so I have no way of telling the query to get accurate info from the second table ( i think that's right)
anyway. below is my query. Can someone please tell me the best way to achieve the results i need to do this properly and have all of those fields populate?
cheers
<?php session_start();
header('Content-type: application/json');
require_once('DbConnector.php');
$connector = new DbConnector();
$customerid = '125';
$sql=( "SELECT DISTINCT reports.id, properties.title, reports.title, reports.date, reports.link FROM reports JOIN properties ON reports.visible = properties.customer WHERE properties.customer ='".$customerid."'" )or die( mysql_error("FAIL!!") );
$result = mysql_query($sql);
while($data = mysql_fetch_assoc($result)) {
$output[] = $data;
}
echo json_encode($output);
?>
try this one
<?php session_start();
header('Content-type: application/json');
require_once('DbConnector.php');
$connector = new DbConnector();
$customerid = '125';
$sql=( "SELECT DISTINCT reports.id, properties.title, reports.title, reports.date, reports.link FROM reports JOIN properties ON reports.visible = properties.visible WHERE properties.customer = '$customerid' " )or die( mysql_error("FAIL!!") );
$result = mysql_query($sql);
while($data = mysql_fetch_assoc($result)) {
$output[] = $data;
}
echo json_encode($output);
?>
so i have this tables and i want to get certain datas for user to view and be able to POST to other page
i cant post images so i have to break this down so please bear with me
1st table
dbo.users
pkey(UserID)
EmployeeName
2nd table
dbo.PC
pkey(PCID)
PC_Number
3rd table
dbo.FA_PC
pkey(FAID)
fkey(UserID)
fkey(PCID)
how could i display the PC_Number of the currently selected $rs->Fields('UserID') in the same form and still be able to post it on printd.php
i dont know how to connect the dbo.users->dbo.FA_PC->dbo.PC
<form action="printd.php" method="post" target="_blank">
<?php
ini_set("display_errors","on");
$conn = new COM("ADODB.Connection");
try {
$myServer = "WTCPHFILESRV\WTCPHINV";
$myUser = "sa";
$myPass = "P#ssw0rd";
$myDB = "wtcphitinventory";
$connStr = "PROVIDER=SQLOLEDB;SERVER=".$myServer.";UID=".$myUser.";PWD=".$myPass.";DATABASE=".$myDB;
$conn->open($connStr);
if (! $conn) {
throw new Exception("Could not connect!");
}
}
catch (Exception $e) {
echo "Error (File:): ".$e->getMessage()."<br>";
}
if (!$conn)
{exit("Connection Failed: " . $conn);}
$sql_exp = "select * from dbo.users";
$rs = $conn->Execute($sql_exp);
echo "<select name='empt'>";
while (!$rs->EOF) {
set_time_limit(0);
echo "<option value=".$rs->Fields('UserID')." >".$rs->Fields('EmployeeName')."</option>";
$rs->MoveNext();
}
$rs->Close();
?>
the join will look like this,
SELECT a.*, c.PC_Number
FROM users a
INNER JOIN FA_PC b
ON a.UserID = b.UserID
INNER JOIN PC c
ON b.PCID = c.PCID
To fully gain knowledge about joins, kindly visit the link below:
Visual Representation of SQL Joins