I am stuck with displaying result into table format. I tried with all options like "pg_fetch_row, pg_fetch_array, pg_fetch_all_columns", but I am not getting results in table format.
The query part is working fine, also I am getting results in XML format, but I need to display it in table format, also it should contain a column heading.
Please can anyone suggest me how to get the results in table format.
My PHP_PostgreSQL code shown in below:
<?
$conn = pg_connect("user=postgres password=nkr#123 host=localhost dbname=test");
if (!$conn) {
echo "An error occured.\n";
exit;
}
$cat=$_POST['cat'];
$subcat=$_POST['subcat'];
echo "Value of \$cat = $cat <br>Value of \$subcat = $subcat \n";
$result = pg_query($conn, "SELECT * FROM $cat JOIN $subcat ON $cat.districtco=$subcat.districtcode");
if (!$result) {
echo "An error occured in result.\n";
exit;
}
echo $result;
if (!$result) {
echo "An error occured in xml_result.\n";
exit;
}
?>
I am using this code to get results in XML:
$xml_result="<resultxml>";
$num = pg_num_fields($result);
while($row = pg_fetch_array($result)){
$xml_result.="<record>";
for ($i=0; $i < $num; $i++)
{
$xml_result .= "<".pg_field_name($result, $i).">".$row[$i]."</".pg_field_name($result, $i).">";
}
$xml_result.="</record>";
}
$xml_result.="</resultxml>";
echo $xml_result;
You do know you should process the result set with a for() loop, don't you?
Although psql will spit the result set from a query optionally in HTML, this only happens because psql was specifically written to do this.
Related
Running a simple search query, which feeds into an android studio textview. When I first managed to display results via .php site, all special characters ([{]}) were on show, but i added this line to remove:
echo json_encode($resultArray, DEFINED('JSON_INVALID_UTF8_IGNORE') ? JSON_INVALID_UTF8_IGNORE : 0);
However, this now means that the results that show are also missing special characters, mainly " ' ". So "You're", is actually showing "Youre".
I have tried to play with the above json query, but with no luck - any idea what I'm doing wrong?
Full code for clarity:
<?php
// Create connection
$con=mysqli_connect("server","user","pass","table");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Select all of our stocks from table 'stock_tracker'
$sql = "
SELECT Task_title
, task_description
FROM TASKS
ORDER
BY RAND () ASC
LIMIT 1
";
// Confirm there are results
if ($result = mysqli_query($con, $sql))
{
// We have results, create an array to hold the results
// and an array to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each result
while($row = $result->fetch_object())
{
// Add each result into the results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Encode the array to JSON and output the results
echo json_encode($resultArray, DEFINED('JSON_INVALID_UTF8_IGNORE') ? JSON_INVALID_UTF8_IGNORE : 0);
echo json_last_error_msg(); // Print out the error if any
die(); // halt the script
}
// Close connections
mysqli_close($con);
?>
I resolved this by adding $cValue=str_replace(array("'",",","."), array("'",",","."), $_POST['contractValue']);underneath the search query. Worked a charm!
I have two tables billing_all and payment_details. I am trying to write php code such that I can run the 2 queries in the same php code and encode their data in json format.I am currently using the following code to achieve that without json encode :-
<?php
include "config.php";
$dbname ="webappdb";
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$dbname);
if(!$con)
{
echo "Connection Error".mysqli_connect_error();
}
else{
//echo "";
}
$sql = "SELECT SUM(total_wt) FROM `billing_all` WHERE date ='15-Apr-2016';";
$sql .= "SELECT pymt_amount, mode_of_pymt FROM `payment_details` WHERE DATE ='15-Apr-2016';";
// Execute multi query
if (mysqli_multi_query($con,$sql))
{
do
{
// Store first result set
if ($result=mysqli_store_result($con)) {
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
printf("%s%s\n",$row[0],$row[1]);
}
// Free result set
mysqli_free_result($result);
}
}
while (mysqli_next_result($con));
}
mysqli_close($con);
?>
How can I encode the received data in json format? I tried something like:-
// Store first result set
if ($result=mysqli_store_result($con))
{
$r = array();
while($row = mysqli_fetch_array($result))
{
array_push($r,
array('total_wt'=>$row[0],
'pymt_amount'=>$row[0],$row[1],
'mode_of_pymt'=>$row[0],$row[1]));
}
echo json_encode(array("result"=>$r));
Which does not give me the expected result.How can I encode the data
in the right way? The following is the structure for the 2 tables
I am new to programming any help is appreciated.Thank you?
<?php
//Joining both tables on the basis of doc_no column
$sql = "SELECT billing_all.SUM(total_wt) AS total
,payment_details.pymt_amount
,payment_details.mode_of_pymt
FROM billing_all
,payment_details
WHERE billing_all.doc_no = payment_details.doc_no
AND billing_all.DATE = '15-Apr-2016'";
// Executing query
$res = mysqli_query($con,$sql);
//initializing array to store result
$rows = array();
//Iterating result and storing each row in $r then array $rows to covert result set into array because json accept array as parameter.
while($r = mysqli_fetch_assoc($res))
{
$rows[] = $r;
}
//print whole array in json format
echo json_encode($rows); ?>
I'm getting some trouble with parsing the output of MySQL query in order to feed Highcharts. The biggest problem is that I would hawe 100+ data series, and I would like to don't refer to each column name in the parsing process, now the desired output would be something like that:
[
{'name':'TS','data':[4349,4375]}
{'name':'time1','data':[503,573]}
{'name':'time2','data':[500,506]}
{'name':'time3','data':[508,649]}
]
But I'm stuck with this output, where all the data are printed in the only first array:
[
{'name':'TS','data':[4349,503,573,500,4375,506,508,649,]}
{'name':'time1','data':[]}
{'name':'time2','data':[]}
{'name':'time3','data':[]}
]
The PHP code that I'm using is the following:
<?php
try {
$con= new PDO('mysql:host=localhost;dbname=test', "root", "");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT TIME_TO_SEC(TS) as TS, TIME_TO_SEC(time1) as time1, TIME_TO_SEC(time2) as time2, TIME_TO_SEC(time3) as time3 FROM time ORDER BY TS";
//first pass just gets the column names
print "[";
$result = $con->query($query);
//return only the first row (we only need field names)
$row = $result->fetch(PDO::FETCH_ASSOC);
//second query gets the data
$data = $con->query($query);
$data->setFetchMode(PDO::FETCH_ASSOC);
foreach ($row as $field => $value){
print "{'name':'$field','data':[";
foreach($data as $row){
foreach ($row as $name=>$value){
print " $value,";
}
}
print "]}";
}
print "]";
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
Any suggestion to how to solve that problem?
Looks like you're using $row multiple times causing the loops to create errors.
Rename your inner $row variable to something else, e.g. $innerData.
foreach ($row as $field => $value){
print "{'name':'$field','data':[";
foreach($data as $innerData){
foreach ($innerData as $name=>$innerValue){
print " $innerValue,";
}
}
print "]}";
}
But there seem to be more problems in your code.
You query the database with the $query, 2 times. You you would get 2 same result sets. Did you miss to insert the second query statement ?
Please include the results the queries will produce in mysql, without php. This way I can improve my answer or other may help you too.
So far I have this code:
<?php
include('config.php');
$sql = "SELECT senderID as receiverID, msg, time
FROM msg
WHERE senderID = 1";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row["receiverID"];
echo $row["msg"];
echo $row["time"];
}
mysql_free_result($result);
?>
Now this simply fetch's the info and stuff, it works the only problem is the processing part. See, I can probably do this so easily in Python, but I am new in PHP, so, if someone could help me, because this is a example of the thing I get returned:
1Hello! How are you?!?!?!876765981admin to user 3574769
Now, I actually was wondering how I would be able to serperate these into its own variable or just print seperately, I am not quiet sure, this is how its suppose to look for a python thing:
firstRow = ['1','Hello! How are you?!?!?!','876765981']
secondRow = ['1','admin to user 3','574769']
Now, I am not so sure about the php structure or code for this.
In php,what you got was:
[
1 => ["receiverId"=>'1',
"msg"=>'Hello! How are you?!?!?!',
"time"=>'876765981'],
2 => ["receivedId"=>'1',
"msg"=>'admin to user 3',
"time"=>'574769']
]
To get the first row
$firstrow = $result[1]
To print it
echo $firstrow["msg"];
The $result is a nested associative array
Ok i got a problem now i want to display a data from the database and display it through a function now how do i do that??
like i have fetched a row from the database and its name is $row_field['data']; and it is correct now i have assigned a variable to it like this $data = $row_field['data']; now if i call it in a function it shows undefined variable even after i assigned it global in the function like this
function fun(){
global $data;
echo $data;
}
but if i assign it a value like 1 or 2 or anything it gets displayed without any error why is that so??
If it displays if you assign it a value like 1 or 2 while still in the global scope, then I can only assume that your database did not return the result you thought it did. Does the database value display if you echo it out outside of the function?
Global is evil. I dont know what you are trying to do, but why dont you just do the query in the function itself?
If you have a column named data and your php call was something like
$result = mysql_query("SELECT data FROM mytable");
while ($row_field = mysql_fetch_assoc($result, MYSQL_NUM)) {
...
}
Then you could replace ... with print $row_field['data'].
Else please provide a snippet of your code where you query the db and retrieve the result.
When learning php try to start with simple things. For example in order to get some data from a database follow the examples from php website.
<?php
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
mysql_free_result($result);
If all this goes well go a little further change a little the while loop.
$myArray = array();
while ($row = mysql_fetch_assoc($result)) {
$myArray[] = $row;
}
mysql_free_result($result);
// now you can start playing with your data
echo $myArray[0];
Small steps...