I am trying to create a single JSON file displaying data from two different tables. I can manage to fetch them, however I don't understand how to concatenate the two arrays. I am new to JSON. Any suggestions/tutorials would be very helpful. Thanks in advance.
Here the expected JSON:
{
"array1":[
{"days":"1","id":"1","image":"image1.jpg, image2.jpg, image3.jpg, image4.jpg"},{"days":"2","id":"1","image":"elephanta.jpg,image2.jpg,image1.jpg,imagica.jpg"},
{"days":"3","id":"1","image":"image3"},{"days":"4","id":"2","image":"image4"}
],
"array2":[
{"id":"1","image_1":"image1.jpg"},
{"id":"2","image_1":"image2.jpg"},
{"id":"3","image_1":"image3.jpg"}
]
}
but the JSON that I get is this:
{
"array1":[
{"days":"1","id":"1","image":"image1.jpg, image2.jpg, image3.jpg, image4.jpg"},{"days":"2","id":"1","image":"elephanta.jpg,image2.jpg,image1.jpg,imagica.jpg"},
{"days":"3","id":"1","image":"image3"},{"days":"4","id":"2","image":"image4"}
]},
{"array2":[
{"id":"1","image_1":"image1.jpg"},
{"id":"2","image_1":"image2.jpg"},{"id":"3","image_1":"image3.jpg"
}
]}
PHP code:
<?php
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","test") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from image_data";
$sql1 = "select * from one";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$result1 = mysqli_query($connection, $sql1) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$imageArray = array();
$imageArray1 = array();
$imageArray["array1"] = array();
$imageArray1["array2"] = array();
while($row =mysqli_fetch_array($result))
{
$tmp = array();
$tmp["days"] = $row["id"];
$tmp["id"] = $row["place_id"];
$tmp["image"] = $row["image"];
array_push($imageArray["array1"], $tmp);
// $imageArray[] = $row;
}
while($row =mysqli_fetch_array($result1))
{
$tmp = array();
$tmp["id"] = $row["id"];
$tmp["image_1"] = $row["image"];
array_push($imageArray1["array2"], $tmp);
// $imageArray[] = $row;
}
echo json_encode($imageArray);
echo ",";
echo json_encode($imageArray1);
//close the db connection
mysqli_close($connection);
?>
If you want the 2 sub arrays to belong to the same array then use only one array and address the 2 sub arrays like this when loading them
$imageArray["array1"][] = $tmp;
and
$imageArray["array2"][] = $tmp;
Amended code
<?php
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","test") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from image_data";
$sql1 = "select * from one";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$result1 = mysqli_query($connection, $sql1) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$imageArray = array(); // <- removed other arrays
while($row =mysqli_fetch_array($result))
{
$tmp = array();
$tmp["days"] = $row["id"];
$tmp["id"] = $row["place_id"];
$tmp["image"] = $row["image"];
$imageArray["array1"][] = $tmp; // <- address array like this
}
while($row =mysqli_fetch_array($result1))
{
$tmp = array();
$tmp["id"] = $row["id"];
$tmp["image_1"] = $row["image"];
$imageArray["array2"][] = $tmp; // <- address array like this
}
echo json_encode($imageArray); // <- only one json_encode
//close the db connection
mysqli_close($connection);
?>
I would have done it this way using stdObject and selecting the specific data from the tables, and using mysqli_fetch_obect() so there is a lot less you have to do woman-draulically
<?php
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","test") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
// only select what you want
$sql = "select id,place_id,image from image_data";
$sql1 = "select id,image from one";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$result1 = mysqli_query($connection, $sql1) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$imageObject = new stdObject();
while($row =mysqli_fetch_object($result))
{
$imageObject->array1[] = $row;
}
while($row =mysqli_fetch_object($result1))
{
$imageObject->array2[] = $row;
}
echo json_encode($imageObject);
?>
Related
this is my code when i run it
$name=$_GET['name'];
$strSQL = "SELECT * FROM category WHERE name LIKE =" .$name;
$rs = mysql_query($strSQL);
// Loop the recordset $rs
$response = array();
while($row = mysql_fetch_array($rs)) {
$product = array();
$product["id"] = $row["id"];
$product["name"] = $row["name"];
array_push($response, $product);
}
echo json_encode($response);
}
error:mysql_fetch_array() expects parameter 1 to be resource, boolean given in while($row = mysql_fetch_array($rs))
it shows error on this line help me to fix this
you have inserted wrong syntax ....use this
$strSQL = "SELECT * FROM category WHERE name LIKE '%$name'";
You need to open a connection to your database. Something like:
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$name=$_GET['name'];
$strSQL = "SELECT * FROM category WHERE name LIKE '%" .$name . "%'";
// $strSQL = "SELECT * FROM category WHERE name = '" .$name . "'";
$rs = mysql_query($strSQL, $conn);
// Loop the recordset $rs
$response = array();
while($row = mysql_fetch_array($rs)) {
$product = array();
$product["id"] = $row["id"];
$product["name"] = $row["name"];
array_push($response, $product);
}
echo json_encode($response);
?>
Also if you are going to use "LIKE" in your sql, you don't use "=".
It is because You are not sending Query matched with your datatype of the name field.
Try below syntax with ''
$strSQL = "SELECT * FROM category WHERE name LIKE '" .$name . "'";
IF you still getting the same error then try this code
$name=$_GET['name'];
$strSQL = "SELECT * FROM category WHERE name LIKE '" .$name . "'";
$rs = mysql_query($strSQL);
if(mysql_num_rows($rs) > 0){
// Loop the recordset $rs
$response = array();
while($row = mysql_fetch_array($rs)) {
$product = array();
$product["id"] = $row["id"];
$product["name"] = $row["name"];
array_push($response, $product);
}
echo json_encode($response);
}
}
else{ echo json_encode(array('msg'=>"No records found")); }
I have been trying to create a PHP function that can display a MySQL table as a HTML table using PHP. So far I am able to output any table I choice, yet I am encountering a problem when the MySQL table contains empty rows, because empty cells result in the HTML tables. My code is as such:
<?php
function getTABLE(){
$db_host = 'HOST.com';
$db_user = 'USER1';
$db_pwd = 'PASSWORD';
$database = 'testdb';
$table = 'FAQTable';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
//// sending query and only result cell that are not NULL
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
echo "<h3><center>Table: {$table}</h3>";
echo "<table border='1'><tr>";
//// printing table headers
for($i=0; $i<$fields_num; $i++){
$field = mysql_fetch_field($result);
echo "<td>{$field->name}</td>";
}
//// printing table rows
while($row = mysql_fetch_row($result)){
echo "<tr>";
//// $row is array... foreach( .. ) puts every element
//// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>";
}
print "</TABLE>";
mysql_close();
}
print getTABLE();
?>
My dilemma is in the "printing table rows" section of the code. I am hoping there is a way in the while($row = mysql_fetch_row($result)) to only accept rows that have values in them. Any ideas?
I have already tried using the following lines with no luck:
$result = mysql_query("SELECT * FROM {$table} WHERE * IS NOT NULL");
$result = mysql_query("SELECT COUNT(id) FROM {$table} where answer IS NOT NULL or answer <>'' ");
$result = mysql_query('SELECT COUNT(*) FROM {$table} WHERE answer <> ""');
$result = mysql_query("SELECT * FROM {$table} WHERE CHAR_LENGTH>0");
$result = mysql_query("SELECT * FROM {$table} WHERE val1 is <> '' ");
$result = mysql_query("SELECT * FROM {$table} WHERE col1 is <> '' ");
//// Outputs funky count in a separate table, but not the desired table with no empty cells
$result = mysql_query("SELECT COUNT(answer) FROM {$table} WHERE CHAR_LENGTH(answer)>0");
$result = mysql_query("SELECT COUNT(answer) FROM {$table} WHERE LENGTH(answer)>0");
$reslts = mysql_query("SELECT * FROM {$table}");
while($row = mysql_fetch_row($reslts)){
$empty_count = 0;
$count = count($row);
for($i = 0; $i < $count; $i++)
if($row[$i] === '' || $row[$i] === 'NULL')
$empty_count++;
$result = ($count);
}
So Thanks To Paul Spiegal for helping with this PHP function that can output any MySQL Table into a HTML Table to be displayed on a website... The working function is as follows, just change the values for the variables to access any MySQL data:
function getTABLE(){
$db_host = 'www.host.com';
$db_user = 'user1';
$db_pwd = 'password';
$database = 'testdb';
$table = 'MyTable';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
//// sending query
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
echo "<h3><center>Table: {$table}</h3>";
echo "<table border='1'><tr>";
//// printing table headers
for($i=0; $i<$fields_num; $i++){
$field = mysql_fetch_field($result);
echo "<td>{$field->name}</td>";
}
//// printing table rows
while($row = mysql_fetch_row($result)){
echo "<tr>";
if (strlen(implode('', $row )) == 0) {
continue;
}else {
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>";
}
}
print "</TABLE>";
mysql_close();
}
print getTABLE();
Using implode() function, you can combine all cells into one string. If that string is empty, you skip printing that row.
while($row = mysql_fetch_row($result)){
if (strlen(implode('', $row)) == 0) {
continue; // skip this empty row
} else {
// TODO: print this row
}
}
I have a php code for some MYSQL interogations,
Code is:
$DBTYPE = 'mysql';
$DBHOST = 'localhost';
$DBUSER = 'tuser';
$DBPASSWORD = 'password';
$DBNAME = 'dbname';
$link = mysql_connect($DBHOST, $DBUSER, $DBPASSWORD);
mysql_select_db($DBNAME);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
//IMG**0**
$hotelc = $hotelCodes[**0**];
$result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode= '$hotelc'", $link);
if(!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
$ImageURL**0** = $row["ImageURL"];
}
//IMG**1**
$hotelc = $hotelCodes[**1**];
$result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode= '$hotelc'", $link);
if(!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
$ImageURL**1** = $row["ImageURL"];
}
..........................
//IMG**x**
$hotelc = $hotelCodes[**x**];
$result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode= '$hotelc'", $link);
if(!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
$ImageURL**x** = $row["ImageURL"];
}
The repeating value on each code line is bolded.
How can i create a Mysql parameterized queries in php.n to avoid write all the lines .I need to extract ~100 $ImageURL from the Flat_table where the $hotelc is found.
For example you have to repeat it $N times:
for($i=0; $i<$N; $i++)
{
$hotelc = $hotelCodes[ $i ];
$result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode= '$hotelc'", $link);
if(!$result) {
die("Database query failed: ".mysql_error());
}
while ($row = mysql_fetch_array($result)) {
${'ImageURL'+$i} = $row["ImageURL"];
}
}
To loop, use for:
for($n=0; $n<100; $n++){
$hotelc = $hotelCodes[$n];
$result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode= '$hotelc'", $link);
if(!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
$ImageURL[$n] = $row["ImageURL"];
}
}
But the inner functions inside the loop is inefficient because mysql query will be executed 100 times. You can query all the ImageURL by using IN() syntax in mysql:
//Wrap all hotelCodes into one string for query, like ["a","b"] to "'a','b'"
$len = count($hotelCodes);
foreach($hotelCodes as $key=>$code){
$hotelCodes[$key] = "'".$code."'";
}
$codesStr = implode(",", $hotelCodes);
$result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode IN (".$codeStr.")", $link);
//Other things...
When writing a function, you look for the commonality. Furthermore, you want to minimize the database interaction. I am, for the sake of deprecation, going to assume $link uses mysqli_connect()
$ImageURL = array();
$list = implode('", "', $hotelCodes);
$result = mysqli_query($link, 'SELECT ImageURL FROM Flat_table where HotelCode IN "' . $list . '"');
while($row = mysql_fetch_assoc($result)) {
$ImageURL[] = $row["ImageURL"];
}
This runs only one query and then loops through the results, generating an associative array. So echo $ImageURL[0]; will output your first URL.
I am a beginner to PHP and MySql. What I wish to do is take a single field value from a MySql table and store it into a php variable. I tried this code but it does not seem to work:
//Get Role ID
$con= mysqli_connect("localhost","root","","darrenvellaedp2");
$result = mysqli_query($con,"SELECT userRoleID FROM tbl_users");
while($row = mysqli_fetch_array($result)) {
echo $row['userRoleID'];
echo "<br>";
}
//make the connection
$con = mysqli_connect("localhost","root","","darrenvellaedp2") or die("Error: " . mysqli_error($con));
//create the query
$result = "SELECT userRoleID FROM tbl_users" or die("Error: " . mysqli_error($con));
//execute the query
$res = $con->query($result);
while($row = mysqli_fetch_array($res)) {
//this will print the userroleid out to the screen
echo $row['userRoleID'];
//this will store it in a variable
$UserRoleID = $row['userRoleID'];
}
It would have been easier for you to just google it as there's a whole section about this on PHP.NET
This is the structure in the database:
items |itemLink
----------------------
Kill Bill|Kill Bill link
Preman |Preman link
This is the code:
$db = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$items = 'SELECT items FROM menus';
$itemLink = 'SELECT itemLink FROM menus';
$itemQuery = $db->query($items);
$linkQuery = $db->query($itemLink);
$fetchItem = $itemQuery->fetchAll(PDO::FETCH_ASSOC);
$fetchLink = $linkQuery->fetchAll(PDO::FETCH_ASSOC);
$merged = array_merge($fetchItem,$fetchLink);
foreach($merged as $entry) {
foreach( $entry as $key => $value ) {
}
}
From the above code, how do I output only the items' datas?
Using the example above you could then do something like this to answer you question
$result = mysql_query('Select * from names');
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo $row["FirstName"] . " " . $row["LastName"] . "<br>";
}
mysql_close($conn);
?>
I would use something like this, not two arrays for something that could be one query. I have shown three methods, using var_dump or print_r will show how each works.
$conn = mysql_connect($hostname, $username, $password);
if (!$conn) {
die('Could not connect to MySQL: ' . mysqli_connect_error());
}
$db_selected = mysql_select_db('sample', $conn);
if (!$db_selected) {
die("Can\t use db : ' . mysql_error()");
}
$result = mysql_query('Select * from names');
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
print_r($row);
}
$result = mysql_query('Select * from names');
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
print_r($row);
}
$result = mysql_query('Select * from names ');
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
print_r($row);
}
mysql_close($conn);