I am trying to create an PHP api in which I am trying to retrieve news storys and all its comments and send it as json.
Here is what i have so far:
$sql = "SELECT * FROM fb_clubnews WHERE clubid='$groupId' AND ori_newsid = 0 ORDER BY newsid DESC LIMIT 10";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$storId = $row["newsid"];
$commentArray = array();
$wallAray[] = array("author"=>$row["userid"],
"story"=>$row["news"],
"date"=>$row["date"],
"time"=>$row["time"],
"matchid"=>$row["fk_match_id"],
"comments"=>$commentsArray);
}
}
My issue is, that I would like to avoid creating a sql inside an sql and loop through it?! The second inside sql would be:
$sql = "SELECT * FROM fb_clubnews WHERE ori_newsid = $storId ORDER BY newsid DESC";
How do I get the $commentArray filled up with comments.
My DB Structure for fb_clubnews looks like this:
int newsid (autoincrement),
int userid,
text news,
int data,
int time,
int matchid,
int ori_newsid
Hoping for help on this and thanks in advance :-)
Something like this:
$sql = "SELECT *, A.newsid as main_news_id FROM fb_clubnews A LEFT JOIN fb_clubnews B ON B.ori_newsid = A.newsid WHERE A.clubid='$groupId' AND A.ori_newsid = 0 ORDER BY A.newsid DESC";
$result = $conn->query($sql);
$wallAray = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$storId = $row["main_news_id"];
if(array_key_exists($storId, $wallAray)) {
$commentArray[] = $wallAray;
} else {
$wallAray[$storId] = array();
$commentArray = array();
}
$wallAray[] = array("author"=>$row["userid"],
"story"=>$row["news"],
"date"=>$row["date"],
"time"=>$row["time"],
"matchid"=>$row["fk_match_id"],
"comments"=>$commentsArray);
}
}
Related
Is it possible to extract highest id from table (in this case 9) and return it as variable $maximum, which I can use later as integer?
You can use MAX() function. Doc can be found here
Try this, It will must work.
$sql = "SELECT id FROM some_table ORDER BY id DESC LIMIT 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id = " . $row["id"];
}
}
You can try with following snippet:
$sql = "SELECT * FROM some_table where id = (select max(id) from some_table)";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id = " . $row["id"];
}
}
Try this, It will must work.
$sql = "SELECT id FROM some_table ORDER BY id DESC LIMIT 1";
$result = $conn->query($sql);
$id = 0;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$id = $row["id"];
}
}
echo $id;
I would like to take data from DB via simple script
<a href='category.php?CAT=Shoes'>Shoes</a>
then simple show all rows with the specific data in "CAT" column like this:
$CAT = $_GET['CAT'];
$sql = "SELECT * FROM Shop WHERE CAT = $CAT" ;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo"
... results
"}}
The problem is that this script does work with INT (for example SELECT CAT = 5 like category.php?CAT=5) but not with VARCHAR (SELECT CAT = Shoes like category.php?CAT=Shoes). Now I'm not sure why is this happening.
With Error: Trying to get property of non-object
$sql = "SELECT * FROM Shop WHERE CAT = '$CAT'"
You need pass $cat as string
$cat = $_GET['CAT'];
$sql = "SELECT * FROM Shop WHERE CAT = '{$cat}'" ;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<pre>' . print_r($row, true) . '</pre><br/>';
}
}
I am trying to get the key value from the multidimensinal array which I have created using .The Array snapshot is given after the Code.
Below is my PHP code-
$selectTicket = "select ticketID from ticketusermapping where userID=$userID and distanceofticket <=$miles;";
$rsTicket = mysqli_query($link,$selectTicket);
$numOfTicket = mysqli_num_rows($rsTicket);
if($numOfTicket > 0){
$allRowData = array();
while($row = mysqli_fetch_assoc($rsTicket)){
$allRowData[] = $row;
}
$key = 'array(1)[ticketID]';
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (".implode(',', array_keys($key)).")";
Array Snapshot-
I need the tickedID value from this array . Like the first one is 49 .
Please help.
change your code like
$selectTicket = "select ticketID from ticketusermapping where userID=$userID and distanceofticket <=$miles;";
$rsTicket = mysqli_query($link, $selectTicket);
$numOfTicket = mysqli_num_rows($rsTicket);
if ($numOfTicket > 0) {
$allRowData = array();
while ($row = mysqli_fetch_assoc($rsTicket)) {
$allRowData[] = $row['ticketID'];
}
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (" . implode(',', $allRowData) . ")";
$ids = array_column( $allRowData, 'ticketID'); //this will take all ids as new array
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (".implode(',', $ids).")";
You should do a single query using JOIN for this:
$query = "
SELECT t.*
FROM ticket t
JOIN ticketusermapping tum
ON t.ticketID = tum.ticketID
AND tum.userID = '$userID'
AND tum.distanceofticket <= '$miles'
";
$stmt = mysqli_query($link, $query);
$numOfTickets = mysqli_num_rows($stmt);
while($row = mysqli_fetch_assoc($stmt)){
var_dump($row); // here will be the ticket data
}
I have a table with a column called 'status'. The defaut value of 'status' is 0. I want to update the value to '1' after using it.
I basically want to check if the status is 0, if it is, do an operation and then change the value to 1.
Here is the code. All works perfectly except that the value of 0 is not changed to 1.
I am a novice so maybe is a very basic mistake :(
<?php
$sql = "SELECT number, status FROM summonerid";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$SummonerID = $row["number"];
$status = $row["status"];
if($status=='0'){
$recentgames=$lol->getRecentGames($SummonerID);
$MatchID1=$recentgames->games[0]->gameId;
$sql = "INSERT INTO matchid (number) SELECT * FROM (SELECT '$MatchID1') AS tmp WHERE NOT EXISTS (SELECT number FROM matchid WHERE number = '$MatchID1') LIMIT 1;";
$sql = "UPDATE summonerid SET status='1' WHERE status='0';"; // THIS IS THE PART THAT DOES NOT WORK WELL
}
}
}
?>
Any help would be highly appreciated
Try this.. you are not executing the sql statements
$sql = "SELECT number, status FROM summonerid";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$SummonerID = $row["number"];
$status = $row["status"];
if($status=='0'){
$recentgames=$lol->getRecentGames($SummonerID);
$MatchID1=$recentgames->games[0]->gameId;
$sql = "INSERT INTO matchid (number) SELECT * FROM (SELECT '$MatchID1') AS tmp WHERE NOT EXISTS (SELECT number FROM matchid WHERE number = '$MatchID1') LIMIT 1;";
$result1 = $conn->query($sql);
$sql = "UPDATE summonerid SET status='1' WHERE status='0';";
$result1 = $conn->query($sql);
}
}
}
?>
Im trying to generate an array but not sure how to go about it.
I'm currently getting my data like so:
$query = mysql_query("SELECT * FROM users WHERE userEmail LIKE 'test#test.com'");
$row = mysql_fetch_array($query);
$query1 = mysql_query("SELECT * FROM categories");
while($row1 = mysql_fetch_array($query1)){
$query2 = mysql_query("SELECT * FROM usersettings WHERE userId = ".$row['userId']." AND usersettingCategory".$row1['categoryId']." LIKE 'y'");
$isyes = mysql_num_rows($query2);
if($isyes > 0){
$cat1 = mysql_query("SELECT * FROM shops WHERE shopstateId = 1 AND (categoryId1 = ".$row1['categoryId']." OR categoryId2 = ".$row1['categoryId']." OR categoryId3 = ".$row1['categoryId'].")");
$cat1match = mysql_num_rows($cat1);
if($cat1match > 0){
while($cat1shop = mysql_fetch_array($cat1)){
$cat1msg = mysql_query("SELECT * FROM messages WHERE shopId = ".$cat1shop['shopId']." and messagestateId = 1");
while($cat1msgrow = mysql_fetch_array($cat1msg)){
echo $cat1msgrow['messageContent']." - ".$cat1msgrow['messageCode'];
$cat1img = mysql_query("SELECT shopimagePath FROM shopimages WHERE shopimageId = ".$cat1shop['shopimageId']);
$imgpath = mysql_fetch_array($cat1img);
echo " - ".$imgpath['shopimagePath']."<br/>";
}
}
}
}
}
But this can cause duplicates when a user has all 3 of a shops categories picked in their preferences. I am trying to find a way to just pull the message ID out instead of the whole thing and put it into an array giving me, for example:
1,3,5,7,1,3,5,2,4,7,8
Then I can just run a separate query to say get me all messages where the ID is in the array, but i am unsure of the most constructive way to build such an array and examples of array from a while loop I have seen do not seem to be what I am looking for.
Is there anyone out there that can push me in the right direction?
Can't help with this code. But if you want an array from a query without duplicate result, you can use " select DISTINCT (id) " in your query or for more simple solution :
$id_arr = array();
$sql = mysql_query("select id from id_table");
while ($id_result = mysql_fetch_array($sql) {
$id = $id_result['id'];
if (!in_array($id, $id_arr)) {
$id_arr[] = $id;
}
}
I have found a much easier way to create the required result. I think at 6am after a hard night coding my brain was fried and I was making things a lot more complicated than I needed to. A simple solution to my issue is as follows:
$query = mysql_query("SELECT * FROM users WHERE userEmail LIKE 'test2#test2.com'");
$row = mysql_fetch_array($query);
$categories = "(";
$query1 = mysql_query("SELECT * FROM categories");
while($row1 = mysql_fetch_array($query1)){
$query2 = mysql_query("SELECT usersettingCategory".$row1['categoryId']." FROM usersettings WHERE userId = ".$row['userId']);
$row2 = mysql_fetch_array($query2);
if($row2['usersettingCategory'.$row1['categoryId']] == y){
$categories .= $row1['categoryId'].",";
}
}
$categories = substr_replace($categories ,")",-1);
echo $categories."<br />";
$query3 = mysql_query("SELECT * FROM shops,messages WHERE shops.shopId = messages.shopId AND messages.messagestateId = 1 AND (shops.categoryId1 IN $categories OR shops.categoryId2 IN $categories OR shops.categoryId3 IN $categories)");
while($row3 = mysql_fetch_array($query3)){
$query4 = mysql_query("SELECT shopimagePath FROM shopimages WHERE shopimageId = ".$row3['shopimageId']);
$row4 = mysql_fetch_array($query4);
echo $row3['messageContent']." - ".$row3['messageCode']." - ".$row4['shopimagePath']."<br />";
}