By using below code
$data = array();
$sql = "SELECT * FROM list";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data['title'] = $row['title'];
$data['name'] = $row['name'];
}
}
echo json_encode($data);
I got 1 result, I can get full result if I do $data[] = $row['title'], but I want to make the result like this
{'title' : ['title 1','title 2'], 'name':['John','Amy']}
You are overwriting the title in each loop iteration. You need to accumulate all the titles and then set it in your data array.
$data = array();
$sql = "SELECT title FROM mainlist";
$result = $db->query($sql);
$titles = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$titles[] = $row['title'];
}
}
$data['title'] = $titles;
echo json_encode($data);
The easiest away is probably this:
$rows = array();
$sql = "SELECT * FROM list";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
}
echo json_encode($rows);
you could achieve by using group_concat on each of the columns in your query. That way you do not need to loop the result again and add column etc...
$sql = "SELECT group_concat(title) as title,group_concat(name) as name FROM list";
$result = $db->fetch(PDO::FETCH_ASSOC);
echo json_encode($result);
Try this:
$titles = array();
$names = array();
$sql = "SELECT title,name FROM mainlist";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$titles[] = $row['title'];
$names[] = $row['name'];
}
}
echo json_encode(array("title" => $titles, "name" => $names));
UPDATE
Updated my code to let you manage an undefined number of columns as result
$out = array();
$sql = "SELECT * FROM wp_cineteca";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
$keys = array_keys($row);
for ($i = 0; $i < count($row); $i++) {
$out[$keys[$i]][] = $row[$i];
}
}
}
echo json_encode($out);
Related
Usually when you do the basic php excercises you just use the following to print data on a blank page:
<?php
include('../includes/dbh.php');
$titulo = mysqli_real_escape_string($conn,$_GET['titulo']);
$sql = "SELECT * FROM proyectos WHERE proyect_name='$titulo'";
$result = mysqli_query($conn, $sql);
$queryResults = mysqli_num_rows($result);
if($queryResults > 0){
while ($row = mysqli_fetch_assoc($result)){
echo "<div>".$row['proyect_name']. "
</div>";
}
}
?>
My question is, if I try to separate and echo out $row proyect_name in another part of the webpage nothing happens. I used both echo and var_dump and yes, the query works but it just doesn't print anything. I am new to this so yes, it may be obvious to you but not to me. I think it may be the while loop, but I do not know how to "blend it in".
<?php
include('../includes/dbh.php');
$titulo = mysqli_real_escape_string($conn,$_GET['titulo']);
$sql = "SELECT * FROM proyectos WHERE proyect_name='$titulo'";
$result = mysqli_query($conn, $sql);
$queryResults = mysqli_num_rows($result);
$data=array();
if($queryResults > 0){
while ($row = mysqli_fetch_assoc($result)){
echo "<div>".$row['proyect_name']. "
</div>";
$data[] = $row;
}
}
foreach($data as value) {
echo $value;
}
// OR
foreach($data as $key => $value) {
echo $key . " - " . $value;
}
?>
Set variable before loop then add $row data to it then loop it out with a foreach loop Does this work??
Use mysqli_fetch_array() - Example
So in your case it would be
<?php
include('../includes/dbh.php');
$titulo = mysqli_real_escape_string($conn,$_GET['titulo']);
$sql = "SELECT * FROM proyectos WHERE proyect_name='$titulo'";
$result = mysqli_query($conn, $sql);
$queryResults = mysqli_num_rows($result);
if($queryResults > 0){
while ($row = $result->fetch_array()){
$rows[] = $row;
}
foreach ($rows as $row) {
echo "<div>".$row['proyect_name']."</div>";
}
}
?>
Good day!
I have a problem here that I can't solve (last 5hrs).
here's my codes:
include 'assets\function\retrieveFunction.php';
$loadGradProgram = array();
$x = count(getCourseInfo());
for($i=0;$i<=$x;$i++){
$loadGradProgram[$i] = getCourseInfo();
}
echo $loadGradProgram[0];
getCourseInfo function
Solution 1:
function getCourseInfo(){
$getInfo = array();
include 'assets\database\connect.php';
$i = 0;
$x = 0;
$sql = "SELECT c.courseID, c.courseCode, c.courseTitle, m.description";
$sql .=" FROM tblcourse as c INNER JOIN tblcoursemajor as m ON c.courseid=m.courseID ORDER BY c.courseID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$getInfo[$i] = $row;
$i++;
}
return $getInfo;
}
}
Result: Array to string conversion
Solution 2:
function getCourseInfo(){
$getInfo = array();
$loadInfo = array();
include 'assets\database\connect.php';
$i = 0;
$x = 0;
$sql = "SELECT c.courseID, c.courseCode, c.courseTitle, m.description";
$sql .=" FROM tblcourse as c INNER JOIN tblcoursemajor as m ON c.courseid=m.courseID ORDER BY c.courseID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$getInfo[$i] = $row;
$i++;
}
$conn->close();
for($x,$x<=$i;$x++;){
$loadInfo[] = implode(',', $getInfo[$x]);
}
return $loadInfo;
}
}
Result: Still the same
and this line causing error: echo $loadGradProgram[0];
I use echo just to see if the query is working.
if you want a multi-dimmentional array like in w3c documentation, you do it like this :
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$getInfo[$i][] = $row['courseID'];
$getInfo[$i][] = $row['courseCode'];
...
$i++;
}
return $getInfo;
then, if you want to diplay an information in the array you can do a foreach loop or a for loop like :
foreach($loadGradProgram as $key => $value) // here the key is useless
{
echo $value[0];
echo $value[1];
}
or directly like this :
echo $loadGradProgram[0][0];
echo $loadGradProgram[0][1];
echo $loadGradProgram[1][0];
I am a completely newbie in programming php I would like to make this code below return many arrays(to flash as3), however I only receive one array.Can anyone please pinpoint what is my mistake here? thanks.
$data_array = "";
$i = 0;
//if(isset($_POST['myrequest']) && $_POST['myrequest'] == "get_characters")
//{
$sql = mysqli_query($conn, "SELECT * FROM ns_users ORDER BY Char_id");
while($row = mysqli_fetch_array($sql))
{
$i++;
$fb_name = $row["Username"];
$fb_id = $row["Fb_id"];
$fb_at = $row["Access_token"];
$fb_sig = $row["Fb_sig"];
$char_id = $row["Char_id"];
if($i == 1)
{
$data_array .= "$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
else
{
$data_array .= "(||)$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
echo "returnStr=$data_array";
exit();
}
When you write your exit insight your loop you stop executing your program and you get only one record. You should set the echo and exit after your while loop.
$data_array = "";
$i = 0;
$sql = mysqli_query($conn, "SELECT * FROM ns_users ORDER BY Char_id");
while($row = mysqli_fetch_array($sql)) {
$i++;
$fb_name = $row["Username"];
$fb_id = $row["Fb_id"];
$fb_at = $row["Access_token"];
$fb_sig = $row["Fb_sig"];
$char_id = $row["Char_id"];
if($i == 1) {
$data_array .= "$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
} else {
$data_array .= "(||)$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
}
echo "returnStr=$data_array";
exit();
Those two last line of your should be outside of your loop:
$data_array = "";
$i = 0;
//if(isset($_POST['myrequest']) && $_POST['myrequest'] == "get_characters")
//{
$sql = mysqli_query($conn, "SELECT * FROM ns_users ORDER BY Char_id");
while($row = mysqli_fetch_array($sql))
{
$i++;
$fb_name = $row["Username"];
$fb_id = $row["Fb_id"];
$fb_at = $row["Access_token"];
$fb_sig = $row["Fb_sig"];
$char_id = $row["Char_id"];
if($i == 1)
{
$data_array .= "$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
else
{
$data_array .= "(||)$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
}
echo "returnStr=$data_array";
exit();
If you would name the columns that you want in the SELECT then it's much simpler. Make sure to use MYSQLI_ASSOC in the fetch:
$sql = mysqli_query($conn, "SELECT Username, Fb_id, Access_token, Fb_sig, Char_id FROM ns_users ORDER BY Char_id");
while($row = mysqli_fetch_array($sql, MYSQLI_ASSOC))
{
$data_array[] = implode('|', $row);
}
echo "returnStr=" . implode('(||)', $data_array);
exit();
I have a query:
$result = mysql_query("SELECT
Left(Right(Base.inputs.Data_inf,4),3) As 'Datas',
count(Base.Data.Data_ID) As `U_Count`
FROM
Base.Data
WHERE
Base.Data_inputs.info = 'TREE'
GROUP BY ");
$rows = array();
while($r = mysql_fetch_array($result)) {
$row[0] = $r[0];
$row[1] = $r[1];
array_push($rows,$row);
}
print json_encode($rows, JSON_NUMERIC_CHECK);
and the result is:
[["Data1",38],["Data2",13]]
I would like the data look more like:
[{"name":"Data1","data":[38]},{"name":"Data2","data":[13]}]
I was trying to use something like this:
$rows = array();
while($r = mysql_fetch_array($sth)) {
$rows['name'] = $r['Datas'];
while($r = mysql_fetch_array($sth)) {
$rows['data'][] = $r['U_Count'];
}
}
But it doesn't work.
Can anyone help?
THNKS
You can traverse the data and store it as an array.
$rows = array();
while($r = mysql_fetch_array($sth)) {
$rows[] = array('name'=>$r['Datas'],'data'=>array($r['U_Count']));
}
Use mysql_fetch_object() instead of mysql_fetch_array()
while($r = mysql_fetch_object($result)) {
...
The query I have below will only show me one result even if there are multiple matching entries (completely or partially matching). How do I fix it so it will return all matching entries:
//$allowed is a variable from database.
$sql = "SELECT `users`.`full_name`, `taglines`.`name`, `users`.`user_id` FROM
`users` LEFT JOIN `taglines` ON `users`.`user_id` = `taglines`.`person_id`
WHERE ( `users`.`user_settings` = '$allowed' ) and ( `users`.`full_name`
LIKE '%$q%' ) LIMIT $startrow, 15";
$result = mysql_query($sql);
$query = mysql_query($sql) or die ("Error: ".mysql_error());
$num_rows1 = mysql_num_rows($result);
if ($result == "")
{
echo "";
}
echo "";
$rows = mysql_num_rows($result);
if($rows == 0)
{
}
elseif($rows > 0)
{
while($row = mysql_fetch_array($query))
{
$person = htmlspecialchars($row['full_name']);
}
}
}
print $person;
Because your overwriting $person on each iteration.
Hold it in a $person[] array if your expecting more then one. Then loop through it with a foreach loop when you intend to output.
Not related but your also querying twice, you only need 1 $result = mysql_query($sql);
Update (Simple Outputting Example):
<?php
$person=array();
while($row = mysql_fetch_array($query)){
$person[] = array('full_name'=>$row['full_name'],
'email'=>$row['email'],
'somthing_else1'=>$row['some_other_column']);
}
//Then when you want to output:
foreach($person as $value){
echo '<p>Name:'.htmlentities($value['full_name']).'</p>';
echo '<p>Eamil:'.htmlentities($value['email']).'</p>';
echo '<p>FooBar:'.htmlentities($value['somthing_else1']).'</p>';
}
?>
Or an alternative way to is to build your output within the loop using concatenation.
<?php
$person='';
while($row = mysql_fetch_array($query)){
$person .= '<p>Name:'.$row['full_name'].'</p>';
$person .= '<p>Email:'.$row['email'].'</p>';
}
echo $person;
?>
Or just echo it.
<?php
while($row = mysql_fetch_array($query)){
echo '<p>Name:'.$row['full_name'].'</p>';
echo '<p>Email:'.$row['email'].'</p>';
}
?>