Friday, 14 December 2018

php - Selecting Query Based on $_POST action to display while loop



last question in here for a week! I need to take a break from this stuff. I'm trying to run a query to extract user data to be used in a while loop. The first query is the default query which would run (or is suppose to run) regardless of $_POST. The second query runs only when ViewAllFriends button is submitted. Here is what I have in form:







Friends of: " . $profile_user_obj->getFirstAndLastName() . "


"; ?>

global $con;
$username = $_GET['profile_username'];

//Default query limits results to 5
$query = mysqli_query($con,"SELECT * FROM users WHERE friend_array LIKE '$username,%' OR friend_array LIKE '%,$username,%' OR friend_array LIKE '%,$username' LIMIT 0,5");

//Query to run if button ViewAllFriends submitted

if(isset($_POST['ViewAllFriends'])) {
$query = mysqli_query($con,"SELECT * FROM users WHERE friend_array LIKE '$username,%' OR friend_array LIKE '%,$username,%' OR friend_array LIKE '%,$username'");

?>



    while ($row = mysqli_fetch_array($query)) {
    $friends = $row['profile_pic'];

    $friend_username = $row['username'];
    ?>












Right now the first query does not run, IOW no profile pics are displayed. However when I submit the View All Friends button, all of the profile pics display. I'm not sure how to evaluate the first query to run as default? I tried the following:



if(empty($_POST[ViewAllFriends])){...}


but this would make the second query an else statement which is not correct logic since it is dependent on a user action.




Any help on this would be really appreciated. Thankyou!


Answer



global $con;
$username = $_GET['profile_username'];

if(isset($_POST['ViewAllFriends'])) {
//Query to run if button ViewAllFriends submitted
$query = mysqli_query($con,"SELECT * FROM users WHERE friend_array LIKE '$username,%' OR friend_array LIKE '%,$username,%' OR friend_array LIKE '%,$username'");
} else {
//Default query limits results to 5

$query = mysqli_query($con,"SELECT * FROM users WHERE friend_array LIKE '$username,%' OR friend_array LIKE '%,$username,%' OR friend_array LIKE '%,$username' LIMIT 0,5");
}


And now remove the extra bracket in:






To:







After the thumbnails.



If it works consider changing the code to use prepared statements instead of writing variable values inside sql queries to prevent from SQL injection attacks.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...