PHP/SQL, Reduce number of queries - php

I am querying a large db in php, and I am not doing it near well enough.
I have the code I need, I simple cannot find a good way to compact these statements.
$q = $_GET['q'];
(dbinit)
$query = "SELECT post_id FROM wp_postmeta WHERE meta_key = '_billing_email' AND meta_value = '$q'";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
$thing = $row['post_id'];
$querys = "SELECT 'meta_value' FROM wp_postmeta WHERE post_id = '$thing' AND meta_key = '_order_number'";
$results = mysql_query($querys);
$rows = mysql_fetch_array($results);
$postid = $rows['meta_value'];
$queryss = "SELECT post_id FROM $table WHERE meta_value = $postid AND meta_key = '_order_number'";
$resultss = mysql_query($query);
$rowss = mysql_fetch_array($result);
$order_id = $rowss['post_id'];
(handling)
}
I am wondering if there is a more efficient way to do these queries, or perhaps have them in one query?

Not sure where $table comes from.
But this JOIN attempt should work:
$q = $_GET['q'];
// ... dbinit ...
$query = "SELECT wpp.post_id,
wpp1.meta_value as orderNumber,
wpp2.post_id as orderId
FROM wp_postmeta wpp
LEFT JOIN wp_postmeta wpp1
ON wpp1.post_id = wpp.post_id
AND wpp1.meta_key = '_order_number'
LEFT JOIN $table wpp2
ON wpp2.meta_value = wpp1.meta_value
AND wpp2.meta_key = '_order_number'
WHERE wpp.meta_key = '_billing_email'
AND meta_value = '$q'";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
(handling)
}
As you can see you can get
$thing = $row['post_id'];
$order_id = $row['orderId'];
inside the loop if needed.

Related

PHP MYSQL Nested While loop skips iterations

Need help to get through this Nested WHILE loop.
The Scenario is
These are the 5 tables in my db
user_info(userid,name,picurl)
user_friends(userid,friend_id)
user_post(userid,post_id,post,time)
user_likes(userid,post_id)
user_comments(userid,post_id)
I want to access user_post table and populate the data in my android application. i can access userid,post_id and time from user_post table and using friend_id of the user from friends table. Now to display a complete post with pic and name i need to access name and picurl of the person who's post it is from user_info table. If i need to display one 1 friends post i can do this simply but when there are couple of friends with more than 1 post i can't get the name and picurl of the user and it displays null in json response.
I'm using Nested While loop for this operation following is my code.
$userid = $_POST['userid'];
$query = "SELECT * FROM user_friend WHERE userid = '$userid'";
$result = mysql_query($query);
$return_arr = array();
$return_arr['newsfeed'] = array();
//Access userid
while($row = mysql_fetch_assoc($result)) {
echo "Friend Name is ".$row['friend_id']. "<br>";
$friend_id = $row['friend_id'];
$friend_id = mysql_real_escape_string($friend_id);
//accessing user_info table to access user info
$picquery = "SELECT * FROM user_info WHERE userid = '$friend_id'";
$picresult = mysql_query($picquery);
$pic = mysql_fetch_assoc($picresult);
$row_array['name'] = $pic['name'];
$row_array['picurl'] = $pic['picurl'];
$query2 = "SELECT * FROM user_post WHERE userid = '$friend_id'";
$result2 = mysql_query($query2);
//Access Posts Against userids
while( $row = mysql_fetch_array($result2) ) {
$post_id = $row['post_id'];
//for number of likes
$likesQuery = "SELECT COUNT(*) as totallikes FROM post_likes WHERE post_id = '$post_id'";
$likesResult = mysql_query($likesQuery);
$likesvalues = mysql_fetch_assoc($likesResult);
$num_of_likes = $likesvalues['totallikes'];
//for number of comments
$commentsQuery = "SELECT COUNT(*) as totalcomments FROM post_comments WHERE post_id = '$post_id'";
$commentsResult = mysql_query($commentsQuery);
$commentsvalues = mysql_fetch_assoc($commentsResult);
$num_of_comments = $commentsvalues['totalcomments'];
$row_array['post_id'] = $row['post_id'];
$row_array['userid'] = $row['userid'];
$row_array['post_text'] = $row['post_text'];
$row_array['post_time'] = $row['post_time'];
$row_array['post_num_likes'] = $num_of_likes;
$row_array['post_num_comments'] = $num_of_comments;
array_push($return_arr['newsfeed'],$row_array);
}
}
date_default_timezone_set('Asia/Karachi');
$date = date(' h:i:s a d/m/Y', time());
echo json_encode($return_arr,JSON_UNESCAPED_SLASHES);
something like this could help. As I don't have any test data I cannot see how it's working. It should display the post_id along with the count of the likes and the comments
SELECT
p.post_id,
COUNT(c.post_id) AS comments_count,
COUNT(l.post_id) AS like_count
FROM user_post p,
user_likes l,
user_comments c
WHERE p.post_id = l.post_id
AND p.post_id = c.post
GROUP BY p.post_id

PHP Why If / Else statement not working in While loop?

This is my code and I don't know why IF/ELSE statement is not working
$user_id = $_POST['user_id'];
$strSQL = "SELECT chat.user_id,max(date) max_date ,user.user_id,user.firstname,user.lastname,user.picture
FROM ( select from_user_id as user_id,date,isread from chat
WHERE to_user_id = '$user_id'
Union select to_user_id as user_id,date,isread from chat WHERE from_user_id = '$user_id' ) as chat join user on user.user_id = chat.user_id
where user.status != 'block' group by chat.user_id order by max_date DESC";
$chatdata = array();
$objQuery = mysql_query($strSQL);
while($row = mysql_fetch_assoc($objQuery)){
$frduser_id = $row['user_id'];
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$picture = $row['picture'];
$strSQL2 = "SELECT isread from chat WHERE to_user_id = '$user_id' and from_user_id = '$frduser_id'
ORDER BY date DESC LIMIT 1";
//array_push($chatdata, $row);
$objQuery2 = mysql_query($strSQL2);
if (empty($objQuery2)) {
$row2 = 1;
$result = array_merge($row, $row2);
array_push($chatdata,$result);
}else{
$row2 = mysql_fetch_assoc($objQuery2);
$result = array_merge($row, $row2);
array_push($chatdata,$result);
}
}
You can use mysql_num_rows to get count of rows inside results.
$objQuery2 = mysql_query($strSQL2);
$objQuery2Rows = mysql_num_rows($strSQL2);
if ( $objQuery2Rows < 1) {
$row2 = 1;
$result = array_merge($row, $row2);
array_push($chatdata,$result);
}else{
$row2 = mysql_fetch_assoc($objQuery2);
$result = array_merge($row, $row2);
array_push($chatdata,$result);
}

Combining multiple MYSQL queries into one with PHP

I know this subject has been covered before, and I've read about a dozen of the links provided by stackoverflow. None match my need.
I have 4 mysql queries using PHP for similar data, I'd like to lower that to one query and maybe put the results in an array that I can access. Here is my current code.
$id = $row[post_id];
$resulttwo = mysql_query("SELECT meta_value FROM wp_postmeta WHERE `post_id` = $id AND `meta_key` = 'length' ");
$temptwo = mysql_fetch_array($resulttwo);
$length[$id] = $temptwo[0];
$id = $row[post_id];
$resultthree = mysql_query("SELECT meta_value FROM wp_postmeta WHERE `post_id` = $id AND `meta_key` = 'location_city' ");
$tempthree = mysql_fetch_array($resultthree);
$trailcity[$id] = $tempthree[0];
$id = $row[post_id];
$resultfour = mysql_query("SELECT meta_value FROM wp_postmeta WHERE `post_id` = $id AND `meta_key` = 'location_state' ");
$tempfour = mysql_fetch_array($resultfour);
$trailstate[$id] = $tempfour[0];
$id = $row[post_id];
unset($tempfour);
$resultfour = mysql_query("SELECT meta_value FROM wp_postmeta WHERE `post_id` = $id AND `meta_key` = 'difficulty' ");
$tempfour = mysql_fetch_array($resultfour);
$difficulty[$id] = $tempfour[0].' difficulty';`
This should work:
$id = $row[post_id];
$result = mysql_query("SELECT meta_key, meta_value FROM wp_postmeta WHERE `post_id` = $id AND `meta_key` IN ('length', 'location_city', 'location_state', 'difficulty')");
$temp = mysql_fetch_assoc($result);
Array $temp will contain the meta_key along with the meta_value which you should be able to call like so $temp[length]. You can check the entire array with print_r($temp);
You should also stop writing new code using mysql_ functions as they are being deprecated and use mysqli_ or PDO instead.
This should be sufficient as you only care about the first row in each query.
SELECT meta_value FROM wp_postmeta WHERE post_id = $id AND meta_key IN ("length", "location_city", "location_state", "difficulty") LIMIT 4;
Damn too late! :/

SQL / PHP How to pull data from a table and place it in variable

Assuming I have a uniqid key in my table and that same key is sent to my site in a get method, how do I pull that specific key out and assign all the data from the table to variables. This is what I have so far but cant seem to figure it out.
$query1 = "SELECT *
FROM todo_item2 as ti INNER JOIN todo_category2 as tc ON ti.todo_id = tc.todo_id'
WHERE todo_id = :todo_id";
$statement1 = $db->prepare($query1);
$statement1 -> execute(array(
'todo_id' =>$id
));
while ($row = $statement1->fetch())
{
$text = $row['todo'];
$cat = $row['category'];
$percent = $row['precent'];
$date = $row['due_date'];
}
You should ready about what execute actually does .. the parameters to execute (and I assume you're using PDO or something similar here) are the tokens of the query. What you want is something like:
$query = " ... WHERE todo_id = ?"
$stmt = $db->prepare($query);
$stmt->execute(array($id));
while ($row = $stmt->fetch()) {
//$row is now an associative array of row values.
}
// Start the Load
$query1 = "SELECT *
FROM todo_item2 as ti INNER JOIN todo_category2 as tc ON ti.todo_id = tc.todo_id
WHERE ti.todo_id = :todo_id";
$statement1 = $db->prepare($query1);
$statement1 -> execute(array(
'todo_id' =>$id
));
// Make Sure the Data Exists
if( $statement1->rowCount() == 0 )
{
die('Please Enter a Valid ID Tag - (id)');
}
while($row = $statement1->fetch())
{
$text = $row['todo'];
$cat = $row['category'];
$percent = $row['percent'];
$date = $row['due_date'];
}

Is it possible to combine these 3 mySQL queries?

I know the $downloadfile - and I want the $user_id. By trial and error I found that this does what I want. But it's 3 separate queries and 3 while loops. I have a feeling there is a better way. And yes, I only have a very little idea about what I'm doing :)
$result = pod_query("SELECT ID FROM wp_posts WHERE guid LIKE '%/$downloadfile'");
while ($row = mysql_fetch_assoc($result)) {
$attachment = $row['ID']; }
$result = pod_query("SELECT pod_id FROM wp_pods_rel WHERE tbl_row_id = '$attachment'");
while ($row = mysql_fetch_assoc($result)) {
$pod_id = $row['pod_id']; }
$result = pod_query("SELECT tbl_row_id FROM wp_pods_rel WHERE tbl_row_id = '$pod_id' AND field_id = '28'");
while ($row = mysql_fetch_assoc($result)) {
$user_id = $row['tbl_row_id']; }
Assuming I am understanding your queries correctly, this should work:
SELECT wp.ID, wpr.pod_id, wpr.tbl_row_id
FROM wp_pods_rel AS wpr
JOIN wp_posts AS wp
ON wp.ID = wpr.tbl_row_id
WHERE wpr.field_id = '28'
AND wp.guid LIKE '%/$downloadfile'
SELECT wp_posts.ID, wp_pods_rel.pod_id, wp_pods_rel.tbl_row_id
FROM wp_posts
JOIN wp_pods_rel ON wp_posts.ID = wp_pods_rel.tbl_row_id
WHERE wp_posts.guid LIKE '%/$downloadfile' AND wp_pods_rel.field_id = '28'

Categories