Loop through two while arrays - php

I am making this post system with like button and count for a social networking site.
My end goal is to loop through these two sets of results together. So that the like counts goes with the individual posts as they loop. The posts and likes are in desc order. Everything matches except I can't get these while fetch results to loop together.
Post loop
<table class="postborder">
<?php
$query1 = "SELECT * FROM tbl_images ORDER BY id DESC";
$result = mysqli_query($connect, $query1);
while($row = mysqli_fetch_array($result)) {
?>
<div id="newpost">
<tr>
<td id="userpost"><?php echo $row['username']; ?> </td>
</tr>
<tr>
<td>
<hr id="hrline">
<img id="newimgpost" src="data:image/jpeg;base64,<?php echo base64_encode($row['name']); ?>" height="500" width="500" class="img-thumnail" />
</td>
<tr>
<td id="textpost">
<?php echo $row['textpost']; ?>
</td>
</tr>
<tr>
<td id="likebutton">
<?php } ?>
</div>
</table>
Like count loop
<?php
//index.php
//session_start();
//SESSION['userid'] = (int)3;
$connect = mysqli_connect("localhost", "root", "", "snazzer");
$query2 = "
SELECT tbl_images.id, tbl_images.textpost,
COUNT(likes.id) as likes,
GROUP_CONCAT(users.name separator '|') as liked
FROM
tbl_images
LEFT JOIN likes
ON likes.postid = tbl_images.id
LEFT JOIN users
ON likes.userid = users.userid
GROUP BY tbl_images.id
ORDER BY id DESC
";
$result2 = mysqli_query($connect, $query2);
if (!$result2) {
printf("Error: %s\n", mysqli_error($connect));
exit();
}
while($row = mysqli_fetch_array($result2))
{
echo '<h3>'.$row["textpost"].'</h3>';
echo '
LIKE';
echo '<p>'.$row["likes"].' People like this</p>';
if(count($row["liked"]))
{
$liked = explode("|", $row["liked"]);
echo '<ul>';
foreach($liked as $like)
{
echo '<li>'.$like.'</li>';
}
echo '</ul>';
}
}
if(isset($_GET["type"], $_GET["id"]))
{
$type = $_GET["type"];
$id = (int)$_GET["id"];
if($type == "postid")
{
$query = "
INSERT INTO likes (userid, postid)
SELECT {$_SESSION['userid']}, {$id} FROM tbl_images
WHERE EXISTS(
SELECT id FROM tbl_images WHERE id = {$id}) AND
NOT EXISTS(
SELECT id FROM likes WHERE userid = {$_SESSION['userid']} AND postid = {$id})
LIMIT 1
";
mysqli_query($connect, $query);
header("location:profile.php");
}
}
?>

I believe you could run two queries together. It's fairly simple; just separate each query with semicolon:
$query = "SELECT * FROM tbl_images ORDER BY id DESC;
SELECT tbl_images.id, tbl_images.textpost, COUNT(likes.id) as likes, GROUP_CONCAT(users.name separator '|') as liked FROM tbl_images LEFT JOIN likes ON likes.postid = tbl_images.id LEFT JOIN users ON likes.userid = users.userid GROUP BY tbl_images.id ORDER BY id DESC";
Or separate the variable by incrementing values, you can read their documentation which explains it here.
$query = "SELECT * FROM tbl_images ORDER BY id DESC";
$query .= "SELECT tbl_images.id, tbl_images.textpost, COUNT(likes.id) as likes, GROUP_CONCAT(users.name separator '|') as liked FROM tbl_images LEFT JOIN likes ON likes.postid = tbl_images.id LEFT JOIN users ON likes.userid = users.userid GROUP BY tbl_images.id ORDER BY id DESC";
Then run your code as you normally would except you change mysqli_query to mysqli_multi_query:
$result = mysqli_multi_query( $connect, $query );
while($row = mysqli_fetch_array( $result )) {
//... code your table here ...//
}
You can also the Object-Oriented method which works pretty well:
$result = $connect->multi_query( $query );
But of course both methods should work fine. Do keep in mind, you may be vulnerable to SQL Injections with mysqli_multi_query. This is PHP's official warning:
Security considerations
The API functions mysqli_query() and mysqli_real_query() do not set a connection flag necessary for activating multi queries in the server. An extra API call is used for multiple statements to reduce the likeliness of accidental SQL injection attacks. An attacker may try to add statements such as ; DROP DATABASE mysql or ; SELECT SLEEP(999). If the attacker succeeds in adding SQL to the statement string but mysqli_multi_query is not used, the server will not execute the second, injected and malicious SQL statement.
Considerations
You could always save both results from your while loop in an array and run them in a foreach loop or have them output individually as $array['key']. Which would be a simple workaround to your queries:
<?php
// first query
$query1 = "SELECT * FROM tbl_images ORDER BY id DESC";
$result = mysqli_query($connect, $query1);
while($row = mysqli_fetch_array($result)) {
$array1[] = $row;
}
// second query
$query2 = "
SELECT tbl_images.id, tbl_images.textpost,
COUNT(likes.id) as likes,
GROUP_CONCAT(users.name separator '|') as liked
FROM
tbl_images
LEFT JOIN likes
ON likes.postid = tbl_images.id
LEFT JOIN users
ON likes.userid = users.userid
GROUP BY tbl_images.id
ORDER BY id DESC
";
$result2 = mysqli_query($connect, $query2);
while($row = mysqli_fetch_array($result2)) {
$array2[] = $row;
}
Once you have those records setup you can now use $array1 and $array2 to setup your table.
To get their keys and setup you can use print_r or var_dump and you will be able to see key => value pairs:
print_r( $array1 );
echo '<br />';
print_r( $array2 );

Related

PHP sort mysql data after the FOREACH loop is completed

I looked for an answer in here, but couldn't find one. I created a way of displaying data from my database in a nice table. Now when I realised I need a way of sorting that data after I executed my query?
first I run main sql query to get basic data:
$sql = "SELECT {$wpdb->users}.ID, firstname.meta_value as first_name,
lastname.meta_value as last_name, webaria_company.meta_value as webaria_company
FROM {$wpdb->users}
INNER JOIN (SELECT user_id, meta_value FROM {$wpdb->usermeta}
WHERE meta_key = 'first_name') as firstname ON {$wpdb->users}.ID = firstname.user_id
INNER JOIN (SELECT user_id, meta_value FROM {$wpdb->usermeta} WHERE meta_key = 'last_name') as lastname ON {$wpdb->users}.ID = lastname.user_id
INNER JOIN (SELECT user_id, meta_value FROM {$wpdb->usermeta}
WHERE meta_key = 'webaria_company') as webaria_company ON {$wpdb->users}.ID = webaria_company.user_id";
$asuserlist = $wpdb->get_results($sql);
Then for each user ID i run a query to get each users results dynamically
<table width="100%">
<thead>
<tr>
<th align="center">Full Name</th>
<th align="center">Company</th>
<th align="center">Attainment Score</th>
</tr>
</thead>
<?php
if (empty($asuserlist)) {
echo "No Users' Data Available Yet!";
}
else {
foreach($asuserlist as $key=>$value){
$result = $wpdb->get_results( "SELECT `score_as` FROM `wattp2_as_score` WHERE `user_id`='".$asuserlist[$key]->ID."' AND `approved`=1 AND `date` > '".$sqldateoneyear."' ORDER BY `date` DESC LIMIT 4" );
// count results in the array of AS SCORE
$countresults = count($result);
// add all results of AS SCORE
$sum = 0;
foreach($result as $key2=>$value){
if(isset($value->score_as))
$sum += $value->score_as;
}
// get the average AS SCORE
$as_score1 = ($sum) / ($countresults);
// round AS SCORE
$as_score_round = round($as_score1);
if ($countresults == 0) {
$as_score_hund = "No Data"; } else {
$as_score_hund = $as_score_round . " over " . $countresults; }; ?>
<tbody><tr><td><?php echo $asuserlist[$key]->first_name . " " . $asuserlist[$key]->last_name; ?></td><td><?php echo $asuserlist[$key]->webaria_company; ?></td><td><?php echo $as_score_hund; ?></td></tr></tbody>
<?php } }?>
</table>
The problem is that i need to be able to sort the table results by the data that is calculated inside the loop and I honestly don't know, whether it is possible or I have to redo my code. I need to be able to sort the table by $countresults and $as_score_hund.
Any advise is welcome, even brief

Select multiple rows from table using checkboxes

I'm trying to use checkboxes for multiple sql query with SELECT.
I have 3 tables, one table for groups one for users and one to connect the user to different groups called groupreluser. Based on what groups are checked, I want it to print out the phonenumber of each user that are a member of those groups.
The checkboxes are created based on the content of the table groups
<form method="post">
<?php
$sql = "SELECT * FROM groups WHERE groupname LIKE '%minor%'";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo '<input type="checkbox" name="checked[]" value="'.$row['group_id'].'">'
. $row['groupname'] . '</br>';
}
}
?>
<input type="submit" name="submit" value="submit">
</form>
Code with the sql query to get the phonenumbers.
if(isset($_POST['submit'])){
$check = $_POST['checked'];
if(!empty($check)){
foreach($check as $sel){
$sel = mysqli_real_escape_string($conn, $sel);
$sql = "
SELECT
groups.group_id,
groups.groupname,
groupreluser.user_id,
groupreluser.group_id,
users.user_id,
users.name,
users.phone
FROM
groupreluser
JOIN
groups
ON
groups.group_id = groupreluser.group_id
JOIN
users
ON
users.user_id = groupreluser.user_id
WHERE
groups.group_id = '$sel'
";
$res = $conn->query($sql);
if($res->num_rows > 0){
while($row = $res->fetch_assoc()){
echo $row['phone'] . '</br>';
}
}
}
}
}
It works fine as long as I dont use the checkboxes but adds the group_id manually in the SELECT statement. Any idea of why this isn't working? Am I missing someting? Dont know if this is the best way to do it though...
Let me know if this is unclear, and I'll try to explain it better
This line probably doesn't work:
$check = mysqli_real_escape_string($conn, $_POST['checked']);
$_POST['checked'] is an array. So you have do the line above for each item in the array.
Your $_POST['submit'] is array so directly passing it to mysqli_real_escape_string won't work. But this approach will do the work:
if(isset($_POST['submit'])){
$check = $_POST['check'];
if(!empty($check)){
foreach($check as $sel) {
$sel = mysqli_real_escape_string($conn, $sel);
$sql = "
SELECT
groups.group_id,
groups.groupname,
groupreluser.user_id,
groupreluser.group_id,
users.user_id,
users.name,
users.phone
FROM
groupreluser
JOIN
groups
ON
groups.group_id = groupreluser.group_id
JOIN
users
ON
users.user_id = groupreluser.user_id
WHERE
groups.group_id = '$sel'
";
$res = $conn->query($sql);
...........

Multiple Select query in while loop

963 rows in user table
872 rows in videos table
In user table (fbid,name) are column names
In video table (fbid,etc..) are colum names.
Using below query, I am fetching name from user table by providing fbid from video table. Below query is only returning 791 rows but it should return 872 instead.
<?php
$counter = 1;
$q = "SELECT * FROM videos GROUP BY fbid ORDER BY score DESC, id ASC";
$r = mysqli_query($conn,$q);
if(mysqli_num_rows($r)>0):
while($row = mysqli_fetch_assoc($r)):
$fbid=$row['fbid'];
$q1 = "SELECT name FROM users WHERE fbid=".$fbid."";
$r1 = mysqli_query($conn,$q1);
while($row1 = mysqli_fetch_assoc($r1)):
$name=$row1['name'];
?>
<?php
$counter++;
endwhile;
endwhile;
endif;
?>
SELECT v.*
, u.name
FROM videos v
JOIN users u
ON u.fbid = v.fbid
ORDER
BY v.score DESC
, v.id ASC;
I modified the code for your inquiry
<?php
$counter = 0;
$q = "SELECT DISTINCT * FROM `videos` ORDER BY `fbid` ASC";
$r = mysqli_query($conn,$q);
if(mysqli_num_rows($r)>0):
while($row = mysqli_fetch_assoc($r)):
$fbid=$row['fbid'];
$q1 = "SELECT * FROM `user` WHERE `fbid`= $fbid ";
$r1 = mysqli_query($conn,$q1);
while($row1 = mysqli_fetch_assoc($r1)):
$name=$row1['nombre'];
echo $name . "<br/>;
?>
<?php
$counter++;
endwhile;
endwhile;
endif;
echo "Total " .$counter;
?>
if you go 791 results may be because some video fbid table is not in the table check how many users this query
SELECT count(fbid) FROM `videos` where fbid NOT IN(SELECT fbid FROM `user`);

Duplicates in php while loop

I am getting a bunch of id's from the database - for each id, I want to do a mysql query to get the relating row in another table. This works fine although I also need to get similiar data for the logged in user. With the mysql query I am using - it duplicates the logged in user data according to how many id's it originally pulled. This makes sense although isnt what I want. I dont want duplicate data for the logged in user and I need the data to come from one query so I can order things with the timestamp.
<?php
mysql_select_db($database_runner, $runner);
$query_friends_status = "SELECT DISTINCT rel2 FROM friends WHERE rel1 = '" . $_SESSION ['logged_in_user'] . "'";
$friends_status = mysql_query($query_friends_status, $runner) or die(mysql_error());
$totalRows_friends_status = mysql_num_rows($friends_status);
while($row_friends_status = mysql_fetch_assoc($friends_status))
{
$friends_id = $row_friends_status['rel2'];
mysql_select_db($database_runner, $runner);
$query_activity = "SELECT * FROM activity WHERE user_id = '$friends_id' OR user_id = '" . $_SESSION['logged_in_user'] . "' ORDER BY `timestamp` DESC LIMIT 15";
$activity = mysql_query($query_activity, $runner) or die(mysql_error());
$totalRows_activity = mysql_num_rows($activity);
echo "stuff here";
}
?>
You can try this single query and see if it does what you need
$userID = $_SESSION['logged_in_user'];
"SELECT * FROM activity WHERE user_id IN (
SELECT DISTINCT rel2 FROM friends
WHERE rel1 = '$userID')
OR user_id = '$userID' ORDER BY `timestamp` DESC LIMIT 15";
You probably want something like this:
$user = $_SESSION['logged_in_user'];
  $query_friends_status = "SELECT * FROM friends, activity WHERE activity.user_id = friends.rel2 AND rel1 = '$user' ORDER BY `timestamp` DESC LIMIT 15";
You can replace * with the fields you want but remember to put the table name before the field name like:
table_name.field_name
I hope this helps.
<?php
require_once "connect.php";
$connect = #new mysqli($host, $db_user, $db_password, $db_name);
$result = $connect->query("SELECT p.name, p.user, p.pass, p.pass_date_change,p.email, p.pass_date_email, d.domain_name, d.domain_price, d.domain_end, d.serwer, d.staff, d.positioning, d.media FROM domains d LEFT JOIN persons p
ON d.id_person = p.id AND d.next_staff_id_person != p.id");
if($result->num_rows > 1)
{
while($row = $result->fetch_assoc())
{
echo '<td class="box_small_admin" data-column="Imię i nazwisko"><div class="box_admin">'.$row["name"].'</div></td>';
echo '<td class="box_small_admin" data-column="Domena"><div class="box_admin">'.$row["domain_name"].'</div></td>';
}}
?>

select row where the slot is the biggest

i need to select one row where slot_left is the biggest. i tried
for ( $i=1;$i<3;$i++) {
$sql5 = "SELECT * from user u where (
select max(slot_left) from company c,user u
where c.id=u.company_id and c.id='$name'
)";
$result5 = mysqli_query($link, $sql5) or die(mysqli_error($link));
while($row=mysqli_fetch_array($result5)) {
// echo the id which the slot_left is the biggest
echo $i['slot_left'];
}
}
but still cannot. please help!
You have to use GROUP BY in your query.
And query execution in Loop is not recommended, it will decrees performance.
Try this.
$sql5 = "select c.id, max(slot_left) from company c,user u
where c.id=u.company_id and c.id='$id' GROUP by c.id";
$result5 = mysqli_query($link, $sql5) or die(mysqli_error($link));
while($row=mysqli_fetch_array($result5)) {
echo $row['slot_left'];
}
SQL can be. You select all rows from DB.
$sql5 = "select max(slot_left) AS slot_left from company c,user u where c.id=u.company_id and c.id='$name' GROUP by u.company_id";
$name variable used in query not set
Variable $i is not array. Array is $row
echo $row['slot_left'];

Categories