Can't combine two queries into one json object - php

I'm trying to combine multiple queries into one result set that I can json_encode. I'm trying to get the user's article and article topic in the first query and the amount of likes in the second query. I'm using AJAX to retrieve the data from the database. My AJAX code looks like this, which doesn't seem to be having any problems:
$.ajax({
url: 'includes/articles/getArticlePreview.php',
type: 'POST',
data: {articleId: articleId, idUsers: idUsers},
dataType: 'json',
success: function(data) {
data.forEach(function(item) {
console.log(item.voteCount);
console.log(item.article);
console.log(item.topic);
});
}
});
and on the back end, I did two separate queries and tried to combine them into one JSON object. My first query is like this:
include '../dbh.inc.php';
$idUsers = mysqli_real_escape_string($conn, $_POST['idUsers']);
$articleId = mysqli_real_escape_string($conn, $_POST['articleId']);
$q = "SELECT COUNT(*) FROM articlevotes WHERE articlevotes.article_id = '$articleId'";
$r = mysqli_query($conn, $q);
while ($row = mysqli_fetch_array($r)) {
$voteCount = $row['COUNT(*)'];
$data['voteCount'] = $voteCount;
}
This returns the vote count just fine. Then, I add my second query:
$query = "SELECT articles.article, articles.topic FROM articles WHERE articles.article_id = '$articleId' AND articles.idUsers = '$idUsers'";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($result)) {
$article = $row['article'];
$topic = $row['topic'];
$data['article'] = $article;
$data['topic'] = $topic;
}
This works fine on its own, as well (when I delete the first query and only encode this one). But when I try to put them all in a $results[] = $data; array and echo json_encode($results);, I'm only getting the "voteCount" in the JSON object and when I go to the network and click on the file that contains the queries, I get the error messages:
Notice: Undefined index: idUsers in C:\xamp\htdocs\Real Website\includes\articles\getArticlePreview.php on line 5
Notice: Undefined index: articleId in C:\xamp\htdocs\Real Website\includes\articles\getArticlePreview.php on line 6
[{"voteCount":"0"}]
Here's the whole query put together:
<?php
include '../dbh.inc.php';
$idUsers = mysqli_real_escape_string($conn, $_POST['idUsers']);
$articleId = mysqli_real_escape_string($conn, $_POST['articleId']);
$q = "SELECT COUNT(*) FROM articlevotes WHERE articlevotes.article_id = '$articleId'";
$r = mysqli_query($conn, $q);
while ($row = mysqli_fetch_array($r)) {
$voteCount = $row['COUNT(*)'];
$data['voteCount'] = $voteCount;
}
$query = "SELECT articles.article, articles.topic FROM articles WHERE articles.article_id = '$articleId' AND articles.idUsers = '$idUsers'";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($result)) {
$article = $row['article'];
$topic = $row['topic'];
$data['article'] = $article;
$data['topic'] = $topic;
}
$results[] = $data;
echo json_encode($results);
I believe I've combined queries like this before, so I'm not sure what I'm doing wrong here. Additionally, is there a better alternative to this than doing two separate queries? Something to combine them in one query? Thanks.

Related

Msqli query array

So I have my code
function GetApi($connection,$UserId){
global $Apicall;
$Apicall = array();
$Apiidquery = mysqli_query($connection, "SELECT ID FROM ` Characterapi` WHERE UserId = '$UserId'");
while($results = mysqli_fetch_assoc($Apiidquery)){
$Apicall[] = $results['ID'];
}
}
The output of this function if I call
$Apicall[0] = 3
$Apicall[1] = 11
and this is the information I want. But now I want to use a function like
function Keyquery($Apicall,$connection ){
global $keyidcall, $keyid ,$Vcode;
$Keyidquery = array();
$Keyidquery = mysqli_query($connection, "SELECT keyid, Vcode FROM `Characterapi` WHERE ID = '$Apicall'");
$results = mysqli_fetch_object($Keyidquery);
$keyid = $results->keyid;
$Vcode = $results->Vcode;
}
This code does run if i set $Apicall ="3"; The issue im having is that I want the first function to get All the IDs associated with $userId in my data base then for each Id run the second function to to get the two specific pieces of information from that query.
In response to the comment below, this is the solution which I would use. However you should be wary of using this method as it does not parameterize the values, and as such not sanitized.
<?php
function Keyquery($Apicall,$connection ){
global $keyidcall, $keyid ,$Vcode;
$string = "ID IN('";
$string.= implode("','", $Apicall);
$string.="')";
$Keyidquery = mysqli_query($connection, "SELECT keyid, Vcode FROM `Characterapi` WHERE ".$string.";");
$results = mysqli_fetch_object($Keyidquery);
$keyid = $results->keyid;
$Vcode = $results->Vcode;
}
?>

Sending a PHP variable through ajax

I want to send the result of an SQL query which is a PHP variable to the index file. Here's from the PHP I want to send from:
$result = mysqli_query($conn, $sql);
$remaining = array();
while($row = mysqli_fetch_array($result)){
array_push($remaining, $row['_id']);
}
echo json_encode($remaining);
?>
<script>
$.ajax({
url: "index.php",
data: {result: result},
dataType: "json",
success: function(result){
}});
</script>
Here is where I want to use the code:
$var_value = $_GET['remaining'];
$values = implode(", ", $var_value);
$sql = "SELECT *
FROM `species`
WHERE `_id` IN (".$valus.") ";
$results = mysqli_query($conn, $sql);
I have tried many methods, running a second ajax call within one already running since the $remaining variable is sent back to a javascript using ajax. $_cookies doesn't work for my webserver. So this seems the best solution. Can anyone see what is going wrong?
As reply to your comment: easy:
session_start(); // important!!
if ( !isset($_SESSION['remaining']) )
{
$result = mysqli_query($conn, $sql);
$remaining = array();
while($row = mysqli_fetch_array($result)){
array_push($remaining, $row['_id']);
}
$_SESSION['remaining'] = $remaining;
}
else
{
$values = implode(",", $_SESSION['remaining']);
/// $_SESSION['remaining'] = null - depends on logic.
$sql = "SELECT *
FROM `species`
WHERE `_id` IN (".$valus.") ";
$results = mysqli_query($conn, $sql);
}

Why is the query returning only one set of data?

The problem I have is when I echo or print the following variables, the data I receive is that of the last business listed in my table only.
At present no matter the listing I click I get the same set of data for the last business returned.
As you can see in the below code I am passing the business_name from the clicked listing to be used in my query to find the relevant business profile information.
$business_name = mysql_real_escape_string($_GET['business_name']);
$query = "SELECT
business_id,
category,
years_recommended,
profile_size,
business_name,
established,
employees,
service,
strengths,
ideal_for,
reassurance
FROM
business_data
WHERE
business_name = '$business_name'
AND
profile_size = 'A'
OR
profile_size = 'B'
OR
profile_size = 'C'
OR
profile_size = 'D'
OR
profile_size = 'E'";
$result = mysql_query($query, $dbc)
or die (mysql_error($dbc));
while($row = mysql_fetch_array($result)) {
$business_id = $row["business_id"];
$profile_size = $row["profile_size"];
$category = $row["category"];
$years = $row["years_recommended"];
$established = $row["established"];
$employees = $row["employees"];
$service = $row["service"];
$strengths = $row["strengths"];
$ideal_for = $row["ideal_for"];
$reassurance = $row["reassurance"];
}
echo...
If you need more information please let me know.
Is there anything wrong with my code?
Many thanks in advance.
Your echo call is outside the fetch loop, so you'll only see the last result even though the others were returned.
while($row = mysql_fetch_array($result)) {
$business_id = $row["business_id"];
$profile_size = $row["profile_size"];
$category = $row["category"];
$years = $row["years_recommended"];
$established = $row["established"];
$employees = $row["employees"];
$service = $row["service"];
$strengths = $row["strengths"];
$ideal_for = $row["ideal_for"];
$reassurance = $row["reassurance"];
// Echo **inside** the loop
echo...
}
If you wish, you can store all the results in a large array, which can then be used anywhere subsequently in your script, as many times as needed:
// Array for all results
$results = array();
while($row = mysql_fetch_array($result)) {
// Append each row fetched onto the big array
$results[] = $row;
}
// Now use it as needed:
foreach ($results as $r) {
echo $r['profile_size'];
print_r($r);
}
your echo should be inside the loop

How to 'append' function variables using the URL and a question about Array's

The first question is how to run a function using the URL, I have the following function:
function do_curl($start_index,$stop_index){
// Do query here to get all pages with ids between start index and stop index
$query = "SELECT * FROM xxx WHERE xxx >= $start_index and xxx <= $stop_index";
Now when I'm trying to do curl.php?start_index=0&stop_index=2 this is not working but when i delete the function and WHERE idnum = 1 it is working.
Now the second question is how 'compile' all the fields from the rows to arrays? I have the current code:
$query = "SELECT * FROM fanpages";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$fanpages_query = '\'http://graph.facebook.com/'.$row['page_id'].'\', ';
echo $fanpages_query;
}
$fanpages = array($fanpages_query);
$fanpages_count = count($fanpages);
echo $fanpages_count;
echo $fanpages_query; returning
'http://graph.facebook.com/AAAAAA', 'http://graph.facebook.com/BBBBBBB', 'http://graph.facebook.com/CCCCCCCC',
(I don't have an idea how to do it in a different way, also when im doing it in such a way i can't delete the final comma which will return PHP-error.)
echo $fanpages_count; returns 1 and like you can see i have 3 there.
Thanks in advance guys!
Do a function call to do the query
function do_curl($start_index, $stop_index){
...
}
$fanpages = do_curl($_GET['start_index'], $_GET['stop_index']);
For your second question, you can use arrays and the implode function to insert commas:
while ($row = mysql_fetch_array($result))
{
$fanpages_query[] = 'http://graph.facebook.com/'.$row['page_id'];
}
return $fanpages_query;
Then use implode to print them out:
echo implode(',', $fanpages);
The whole code:
function do_curl($start_index = 0, $stop_index = null) {
$queryIfThereIsNoStartIndex = '';
$queryIFThereIsNoStopIndex = '';
$queryIfBothStartAndStopIndexAreMissing = '';
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$fanpages_query[] = 'http://graph.facebook.com/'.$row['page_id'];
}
return $fanpages_query;
}
$fanpages = do_curl($_GET['start_index'], $_GET['stop_index']);
$fanpages_count = count($fanpages);
echo implode(',', $fanpages);
And you should totally use mysql_escape_string for escaping the values you add to the query.

Web page not loading with PHP-MySQL code while outputting JSON

I am using the code below to get information from a database and make it into JSON (it may be wrong).
Unfortunately it won't load in my web browser, it just says it's loading but it doesn't finish. Please can you tell me what I am doing wrong.
$query = mysql_query("SELECT * FROM Posts ORDER BY date DESC") or die(mysql_error());
$array = array();
while ($row = mysql_fetch_assoc($query)) {
$array[] = $row;
$postID = $row['id'];
while ($ra = mysql_fetch_assoc(mysql_query("SELECT * FROM Comments WHERE postID = '$postID'"))) {
$array['comments'] = $ra;
}
while ($rd = mysql_fetch_assoc(mysql_query("SELECT * FROM Likes WHERE postID = '$postID'"))) {
$array['likes'] = $rd;
}
}
echo json_encode($array);
You are executing mysql_query in the infinite loop:
on each iteration you query the database, and fetch the first row. Change it to
$res = mysql_query("SELECT * FROM Comments WHERE postID = '$postID'");
if (!$res)
{
// handle error
}
while ($ra = mysql_fetch_assoc($res))
{
....
}
And the same for your second query.

Categories