<?php
$username = "trainerapp";
$password = "password";
$hostname = "localhost";
$link = #mysql_connect($hostname, $username, $password);
if (#mysql_select_db("trainer_registration")) {
$select_query_num = #mysql_query("select id from program_details");
$num_rows = #mysql_num_rows($select_query_num);
while ($row = #mysql_fetch_assoc($select_query_num)) {
$j = $row['id'];
$select_query = #mysql_query("select id,program_name,company,date_prog from program_details where id = $j");
$fetch_query = #mysql_fetch_assoc($select_query);
$id = $fetch_query['id'];
$pgmname = $fetch_query['program_name'];
$comp = $fetch_query['company'];
$datephp = $fetch_query['date_prog'];
$arr[] = array(
$id,
$pgmname,
$comp,
$datephp
);
}
echo json_encode($arr);
}
?>
CURRENT OUTPUT:
[["1","Sample","Apple","2015-05-27"],["2","Sample 2","Lenovo","2015-05-28"],["14","3","3","09-29-2015"]]
I don't understand this output.
Questions:
What does json_encode actually return? A string of all values or an array separated by ','? Because when I tried str.length() in js file, it returned 126
How do I get output like single rows
["1","Sample","Apple","2015-05-27"]
["2","Sample 2","Lenovo","2015-05-28"]
["14","3","3","09-29-2015"]
in an array in javascript because I need to insert them in html under separate columns. That is, 1,2,14 under the column "ID", sample, sample 2, 3 under the column "Program name", and so on.
Please help on parsing this array.
1 - http://php.net/manual/en/function.json-encode.php all is detailled there.
2 - Convert php array to Javascript it will help you.
3 - If you need an array, why do you use json_encode in your code.
4 - Do you know why do you use # in many places? It's really bad to code like this.
Related
I am still new to PHP. I have tried a few stuff, but I just can't get it to work.
Question: I want all the data from my users table to be in a string, separated by comma. Then when the ID is 2 to be ; for net new row, so on and so forth. If someone can please help me.
$server = "localhost";
$user_name = "root";
$password = "";
$database = "users";
$conn = new mysqli($server, $user_name, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM Users;";
$result = $conn ->query($sql);
while($row = mysqli_fetch_array( $result )) {
$rows = implode (";",$result);
$array = $rows;
echo $array;
}
Question2: But if I want first row of DB data to be, separated and then at the end with a ;. How would I do that?
Output: The output of this code is:
Warning: implode(): Invalid arguments passed
You've simply used the wrong variable in your call to ìmplode.
You've assigned all the columns as an array to $row - but you're trying to implode $result.
Update that line to this:
$rows = implode(";", $row);
Let's say your user table has 2 fields Firstname and Lastname. What I understood from your question is you want your output to be something like
$array = ['steve,jobs;', 'mark,zukerberg;'];
To achieve this you can append ';' at the end of the string.
while($row = mysqli_fetch_array( $result )) {
$rows = implode(',',$row) . ';'; //you have named this variable $rows but it is going to have data of a single row
$array = $rows; //you could directly var_dump($rows) instead of assigning it to a new variable
echo $array; //you could rather use var_dump($array) for this
}
i want to use json result in some calculation but whatever i try it didn't work.
<?php
//product id
$gp_id=$_GET['gp_id'];
//Importing the database connection
require_once('dbConnect.php');
$sql2 = "SELECT sum(rating_score) AS total_rate ,count(consumer_id) AS consumer
FROM productrate
WHERE gp_id='$gp_id'";
//Getting result
$result = mysql_query($sql2);
//Adding results to an array
$res = array();
while($row = mysql_fetch_array($result))
{
array_push($res, array(
// "gp_id"=>$row['gp_id'],
"total_rate"=>$row['total_rate'],
"consumer"=>$row['consumer']
)
); }
//Displaying the array in json format
$objJson=json_encode($res);
echo $objJson;
//calculate avg rate of specific product
$avg_rate = (int)"total_rate" / (int)"consumer";
echo $avg_rate ;
?>
as you see at the end i try to do some calculation but it didn't work.
this is the output...
[{"total_rate":"18","consumer":"4"}]
Warning: Division by zero in C:\xampp\htdocs\totalrate\highRate.php on line 33
$objJson=json_encode($res); makes json string. For example '{"a":1,"b":2,"c":3,"d":4,"e":5}'. You cannot use it like variables. Its string.
$avg_rate = "total_rate" / "consumer";
Looks like you trying to divide a string with another string.
Try using the array element instead, like:
$avg_rate = $res["total_rate"] / $res["consumer"];
finally i solve the problem ...
//product id
$gp_id=$_GET['gp_id'];
//Importing the database connection
require_once('dbConnect.php');
$sql2 = "SELECT sum(rating_score) AS total_rate ,count(consumer_id) AS consumer
FROM productrate
WHERE gp_id='$gp_id'";
//Getting result
$result = mysql_query($sql2) or die(mysql_error());
//Adding results to an array
$res = array();
while($row = mysql_fetch_array($result))
{
array_push($res, array(
"avg_rate"=>$row['total_rate']/ $row['consumer'],
"total_rate"=>$row['total_rate'],
"consumer"=>$row['consumer']
)
); }
//Displaying the array in json format
$objJson=json_encode($res);
echo $objJson;
?>
Hello in my php code mysql only fetches 1 result which is in the last rather than all please help me why its doing like this here is my code
$requesthost = "SELECT * FROM tblvhost";
$reshost = mysql_query($requesthost);
while($rowhost=mysql_fetch_array($reshost)) {
$hostvid = $rowhost['vh_id'];
$hostname = $rowhost['vh_name'];
}
You’re overriding the data within each loop iteration:
while($rowhost=mysql_fetch_array($reshost)) {
$hostvid = $rowhost['vh_id']; // overwritten
$hostname = $rowhost['vh_name']; // overwritten
}
To collect all the data you probably want to append them to an array:
$hostvid = array();
$hostname = array();
while($rowhost=mysql_fetch_array($reshost)) {
$hostvid[] = $rowhost['vh_id']; // insert into array
$hostname[] = $rowhost['vh_name']; // insert into array
}
You are overwrite your variables in your loop. Store them into an array.
while ($rowhost = mysql_fetch_array($reshost)) {
$row[] = array(
'hostvid' => $rowhost['vh_id'],
'hostname' => $rowhost['vh_name']
);
}
var_dump($row);
this is a good question plus its a learning curve for the ones that are new that run into these types of issues
you're code
$requesthost = "SELECT * FROM tblvhost";
$reshost = mysql_query($requesthost);
while($rowhost=mysql_fetch_array($reshost)) {
$hostvid = $rowhost['vh_id'];
$hostname = $rowhost['vh_name'];
}
looks good, but what you are doing with or how are you applying hostvid? or hostname? you can just do
while($rowhost=mysql_fetch_array($reshost)) {
$rowhost['vh_id']; //do something with the var that's getting mysql field data
$rowhost['vh_name']; //same applies here. using $rowhost will continue to to provide data depending on what you have in the db. so you're OK.
}
if you want to store the data in an array for later use outside of the loop you can follow what #mudasobwa posted. good answer.
So I am getting the elements from the MySQL table and I want to make them into an array and then merge that array which gets encoded into JSON. It doesn't error but it only is displaying an empty JSON string'[]'
<?php
include "connectdb.php";
$banned = array();
$query = mysql_query("SELECT * FROM banned");
while($row = mysql_fetch_array($query)) {
$user = array(
UserId => $row["userId"],
Reason => $row["reason"],
);
array_merge($banned,$user);
}
echo json_encode($banned);
?>
It looks like you're just trying to add a $user array, which you're using as sort of an object, to the $banned array.
To push something onto an array, use array_push, or this notation:
$banned[] = $user;
Your php looks fine, so we are doen to your database or query. Put this line after your query:
echo mysql_num_rows($query);
See if this number is 0. If it is, you are not actually getting any information back from your query.
If that doesn't help locate the problem, keep using echo liberally, at ever line if you need to. See what is happening and why. This is the way you diagnose a problem. Echo the $row["userId"], echo the $banned variable before encoding, although that will take a var_dump(). Echo everything and you'll locate your problem.
First build a multi dimensional array, and encode it for JSON.
<?php
include "connectdb.php";
$banned = array();
$query = mysql_query("SELECT * FROM banned");
while($row = mysql_fetch_array($query)) {
$user = array(
UserId => $row["userId"],
Reason => $row["reason"],
);
$banned[] = $user;
}
echo json_encode($banned);
?>
Then if you need to, you can still access the array like this:
for ($i = 0; $i < count($banned); $i++) {
$UserID = $banned[$i]['UserID'];
$Reason = $banned[$i]['Reason'];
//Do something with this data like:
echo "User ".$UserID." was banned for ".$Reason;
}
I have a table set up in MySQL with two columns:
ID (auto_increment)
recentlyplayed (VARCHAR, set up like "1 44" or "2 140", etc)
I'm trying to get the mysql data into an array and compare it to something defined outside MySQL. But it doesn't seem to work for some reason. Here is my code:
$whichPlaylist is a 1 character INT, and $num is a 3 character INT.
//Note: These values are actually received through file_get_contents('textfile.txt');
$whichPlaylist = "1";
$num = "44";
//Combine playlist number and video number
$joint = $whichPlaylist. "" .$num;
//Insert joint var into Mysql database
mysql_query("INSERT INTO recentlyplayed (numplayed) VALUES('$joint') ");
$query = "SELECT * FROM recentlyplayed";
$result = mysql_query($query) or die ("no query");
while($row = mysql_fetch_array($result))
{
$stored[] = $row['1'];
}
if (in_array($joint, $stored['1'])){
$reroll = 1;
}
echo $reroll;
Even if the same value of $joint is in the MySQL table, $reroll doesn't echo 1. Could this because of extra spacing when inserting the $joint variable? I'm actually getting the $whichPlaylist and $num from a text file that has a new line after the number. Any help is appreciated. :)
Move the While End braces after if statement, and see if it works.
Try this code in your script:
$stored = array();
while($row = mysql_fetch_array($result)) {
$stored[] = $row[1];
}
if (in_array($joint, $stored)){
$reroll = 1;
}
The array is $stored (not $stored['1']).