Take data from URL in MySql DB - php

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/>';
}
}

Related

select maximum value of id from mysql table and save it as variable

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;

How to compare value in two tables from the same database

I have been trying to compare value in a table with another value in another table but only the else part is executing.
<?php
$sql = "SELECT * FROM user WHERE user_id=$row[user_id]";
$result = $conn -> query ($sql);
if ($result -> num_rows > 0) {
while ($row = $result ->fetch_assoc()) {
$sql1 = "SELECT * FROM jobpost WHERE jobpost_id=$_GET[id] ";
$result1 = $conn -> query ($sql1);
$row_count = mysqli_num_rows($result);
$row1_count = mysqli_num_rows($result1);
$remaining_rows = min($row_count, $row1_count);
$row = mysqli_fetch_assoc($result);
$row1 = mysqli_fetch_assoc($result1);
if($row["experience"] > $row1["experience"])
{
//some code to display something
echo "1";
}
else
{
echo "2";
}
} }
?>
Welcome to SO, it is hard to read your source code. You can use a simple query like this:
SELECT IF(u.experience > j.experience,1,0) FROM
(
(SELECT experience FROM user WHERE user_id = 1) u
JOIN
(SELECT experience FROM jobpost WHERE jobpost_id = 8) j
)
Try this query here: http://sqlfiddle.com/#!9/1742c0
Please check our datasource. Maybe the else case is correct.

Get story and all its comments in 1 query

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);
}
}

Php script to filter by name the results from database

I want to display hospital names from database by two ways:
By Selecting city.
By entering the name of hospital in search bar.
I wrote below php script. The 1st part works fine and shows all hospitals from a selected city, but 2nd part doesn't work for me. There is no error displayed. Need help with this. Did i not put the 'if' conditions in the right place? Or I missed something else?
if (isset($_POST['search'])) {
if (isset($_POST['search-by-city'])) {
$city_id = $_POST['search-by-city'];
$query = "SELECT * FROM `hospitals` WHERE `City_ID` LIKE '%$city_id%'";
$result = mysqli_query($con,$query);
if (mysqli_num_rows($result) == 0) {
echo '<h2>No recod Found</h2>' ;
}
}
if (isset($_POST['search-by-name'])) {
$hospital_name = $_POST['search-by-name'];
$query = "SELECT * FROM `hospitals` WHERE `Name` LIKE '%$hospital_name%'";
$result = filterTable($query); {
if (mysqli_num_rows($result) == 0) {
echo '<h2>No recod Found</h2>' ;
}
}
while($row = mysqli_fetch_array($result)){
$city_id = $row[3];
$query = "SELECT `Name` FROM `cities` WHERE `ID` LIKE '$city_id'";
$result2 = mysqli_query($con,$query);
$row2 = mysqli_fetch_row($result2);
$city_name = $row2[0];
echo '
<h3>'.$row[1].'</h3>
<h4>'.$city_name.'</h4>
';
}
}

Creating an array of IDs from a while loop

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 />";
}

Categories