Combining the contents of two array tables

I am attempting to retrieve the status of all users from my website. Here is my table https://i.stack.imgur.com/2I3xi.png

When another user adds me, their username is added to user1. If I add another user, my username gets added into user1 and theirs into user2.

Therefore, I need to gather all the IDs from user1 and user2 where accepted is 1.

This is how I do it:

$id = $_SESSION['user_id'] ;
$yes = '1';
$query = $db2->prepare("SELECT * FROM friend_requests WHERE (user1='".$id."' OR user2='".$id."') AND accepted = '".$yes."'");
$query->execute();
foreach ($query as $row) {
    print $row['user1'] . "\t";
    print $row['user2'] . "\t";

}

Now that I have $row['user2'] and $row['user1'], is there a way to combine them into one so I can simply use a pdo loop to select status where id equals that?

I want to retrieve all statuses where id = $row['user1'] or $row['user2'], but I prefer not to use OR in my pdo select statement.

Answer №1

You have the option to modify your SQL query in the following way:

"SELECT id, (CASE WHEN user1 = $id THEN user2 ELSE user1 END) as user, time FROM friend_requests WHERE (user1 = $id OR user2 = $id) AND accepted = 1"

By implementing this change, you will receive only the approved friends associated with the user identified by the ID $ID.

To see the demonstration of this approach, visit:

UPDATE: It is advisable to bind parameters to safeguard against SQL injection, although this topic extends beyond the current discussion.

UPDATE 2: Regarding your subsequent inquiry, there are two alternative methods available - either conduct two separate loops or utilize fetchAll() if the table size is relatively small compared to the memory capacity.

$id = $_SESSION['user_id'] ;
$query = $db2->prepare("SELECT (CASE WHEN user1 = :userid THEN user2 ELSE user1 END) as user FROM friend_requests WHERE (user1 = :userid OR user2 = :userid) AND accepted = 1");
$query->bindParam(':userid', $id, PDO::PARAM_INT);
$query->execute();
$friends = $query->fetchAll(PDO::FETCH_ASSOC);
$friends[] = array('user'=>$id);
foreach ($friends as $k=>$friend) {
    echo $friend . "\t";
}

Answer №2

If you're looking for a way to combine results from two tables, you can employ the UNION method in your SQL query:

<?php

$id = $_SESSION['user_id'] ;
$yes = '1';
$query = $db2->prepare("SELECT id,user2 AS `user` FROM `friend_requests` WHERE user1=:user1 AND accepted={$yes} UNION SELECT id,user1 AS `user` FROM `friend_requests` WHERE user2=:user2 AND accepted={$yes}");
$query->bindParam(':user1', $id, PDO::PARAM_INT);
$query->bindParam(':user2', $id, PDO::PARAM_INT);

$query->execute();
foreach ($query as $row) {
    print $row['user'] . "\t";
}

To see this method in action, you can check out this example on SqlFiddle.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

PHP functioning on one server yet malfunctioning on a different server

Currently in the process of transferring a WordPress website from JustHost server to VPS (Debian 8). The installation of WordPress was successful, and all pages are functioning correctly, except for the homepage, which appears blank. This is the only page ...

How can Laravel 4's Eloquent be used to implement 'offset' instead of 'page' in the ->paginate() method?

Currently, I am in the process of transferring an existing REST API to Laravel 4.1, where the API relies on the offset querystring parameter to define the offset for the records. My aim is to utilize Eloquent's default paginate(), but it recognizes t ...

Utilizing PHP for loading a fresh webpage within a specific div element of an existing page through AJAX

<!doctype html> <head> <title>Homepage</title> <style> #header{background-color:#09C; width:100%; height:100px;} #logoandsearch{background-color:#603; width:400px; height:40px; float:left; margin-top:30px; margin-left:1 ...

Tips for rounding small decimal numbers in PHP

I need help with rounding a specific number to two decimal places. The number is: 0.108504578471184 To achieve this, I tried using the round() function in PHP as shown below: round(0.108504578471184, 2) The expected result should be: 0.11 However, th ...

"Encountered error converting array to string while attempting to swap out two elements

Here is the code snippet I am working with: <?php $url_constructor = "http://myecommerce.dev/edit/article_name/article_id"; $cart_line_link = str_replace($url_constructor, array( 'article_id', 'article_name' ) , array( $ ...

Error 404 occurred after transferring the website from a Linux/Apache server to a Windows 2008

After migrating the website from RedHAT/CloudLinux/Apache 2.2 to Windows 2008 R2/IIS7, I encountered a 404 error: "404 - File or directory not found. The resource you are looking for might have been removed, had its name changed, or is temporarily unavaila ...

Passing array data from JavaScript to PHP using POST method in Joomla 3.x

Looking for a way to send an array from JavaScript to a Joomla 3.x PHP file? var data = ['foo', 'bar']; $.post('index.php?option=component&view=componentview&Itemid=123&tmpl=component&layout=xlsx', {'xls ...

Resolving the Node.js and MySQL duplication problem

Currently, I am utilizing the mysql module for nodejs and my application is functioning with multiple workers using the cluster package. Each worker retrieves tweets and saves them in the database, ensuring that each record is distinct based on the tweet_ ...

php code for locating a substring within a larger string

I need assistance with accessing a mysql database and extracting a specific segment of code from a column. The content in the column looks something like this: <image identifier="540aa2ad-9a8d-454d-b915-605b884e76d5"> <file><![CDATA[image ...

Upon submission of the form, trigger an email to be sent and simultaneously open a

I need my form to simultaneously open a window and send the form data via email when submitted. <form action="" method="post" id="form" onsubmit="paymentfunc();return false;"> Submit button: <input type="submit" value="Purchase" class="btn" id= ...

How can I generate a daily report for an Employee that includes all dates within a specified range, even for dates when no data was entered?

Greetings! Currently, I am in the process of developing an app (API) using Laravel for efficient employee management. To provide a clearer understanding of my requirements, I will walk you through the steps involved. When adding or registering an Employee ...

"Utilize the power of the ajaxform jQuery plugin to automatically reset form fields

Initially, I'd like to emphasize that this is an original inquiry. My predicament is as follows: I have a chatroom php script where I utilize the ajaxForm jQuery plugin to seamlessly send new messages without having to reload the entire page. Howev ...

``There seems to be an issue with the redirect header function in the PHP

Setting up my test site on a local host, I included an ajax request in one of my java-script files to a php script. if(hIF == "true"){ $.ajax({ type: "POST", url: "log_in/login.php", data: {name: userName, pwd: password}, ...

Obtaining values from a jQuery slider for the price range

<meta charset="utf-8"> <title>jQuery UI Slider - Range slider</title> <link rel="stylesheet" href="jquery.ui.all.css"> <script src="jquery-1.7.1.js"></script> <script src="jquery.ui.widget.js">< ...

Creating personalized flash messages in CakePHP

I recently came across a feature in the CakePHP Book where you can create your own customized setFlash messages using an element. However, I'm unsure of what to include inside the element and how to pass different content. For instance, let's sa ...

Submitting a specific group of form inputs using ajax involves selecting the desired elements within the form

My task involves dealing with a large form that needs to be submitted in PHP, which poses a challenge due to the maximum input variable limits in PHP +5.3 as discussed on this Stack Overflow thread. Instead of submitting everything from the form, I only n ...

Integrating PHP code into a React.js application can provide

I am currently integrating react.js into a section of my app and exploring the possibility of embedding some PHP code into react.js. This would allow me to avoid having to completely rewrite the backend that was originally written in PHP. Here's an ex ...

Updating a dropdown select in jQuery using AJAX and returning an empty string when it changes

Could someone please help me figure out what I am doing wrong here? When I use console.log(), it is returning an empty string instead of an array. I am trying to update the second select box when the onChange event is triggered on the first select box, bu ...

A guide on combining two parameters using jQuery in a link for CodeIgniter

I am attempting to pass two parameters through jQuery in the href attribute of an a link, which I will then use in CodeIgniter. Here is my current code: $("#user_comment_show").append("<li>"+...+'<a id="remove_link&qu ...

Refreshing the page triggers the callback function that retrieves the checkboxes selected in a Kendo treeview component

How can I retain the selected checkboxes after refreshing the page? Is there a way to achieve this using AJAX when submitting data to a database and then reloading the page? AJAX //AJAX call for button $("#primaryTextButton").kendoButton(); va ...