Reputation: 45
Working CODE :)
Is this the right way to do this? or am i missing some more security code??
What went wrong? the first if condition was: if (isset($_POST['submit']) {
The code..
}
i don't know how but it wouln'd work liek that, so i changed it to the code below and now it works!! :)
<?php
if (isset($_POST['username']) || isset($_POST['locatie']) || isset($_POST['geslacht']) || isset($_POST['online'])) {
$name = mysqli_real_escape_string($server, $_POST['username']);
$waar = mysqli_real_escape_string($server, $_POST['locatie']);
$sex = mysqli_real_escape_string($server, $_POST['geslacht']);
$status = mysqli_real_escape_string($server, $_POST['online']);
$sql= "SELECT * FROM users WHERE 1=1";
if (isset($_POST['username'])) {
$name = $_POST['username'];
$sql .= " and username LIKE '%$name%'";
}
if (isset($_POST['locatie'])) {
$name = $_POST['locatie'];
$sql .= " and locatie LIKE '%$waar%'";
}
if (isset($_POST['geslacht'])) {
$name = $_POST['geslacht'];
$sql .= " and geslacht LIKE '%$sex%'";
}
if (isset($_POST['online'])) {
$name = $_POST['online'];
$sql .= " and online LIKE '%$status%'";
}
$sql .= " ORDER BY RAND()";
$result_set=mysqli_query($server,$sql) or die(mysqli_error($server));
//echo $sql;
echo '<div class="col-sm-12">';
while($row=mysqli_fetch_array($result_set)) {
echo '<div class="col-sm-2">';
echo '<center><img class="img-vrienden" src=' . $row['prof_pic'] . ' /><br>' . $row['username'].'</center>';
echo '</div>';
}
echo '</div>';
}
?>
Upvotes: 3
Views: 71
Reputation: 45
I have fixed it!!! and it works great..! shout out to @Adam Silenko for the dynamic where clause.. :)
AND @luweiqi thanks for the SQL injection help and the <input>
instead of the <button>
Upvotes: 0
Reputation: 6896
You cannot have a echo()
in a echo()
:
echo '<img class="img-vrienden" src="echo $row["prof_pic"]" /><br>
echo $row["username"]';
You'll need to concat the string with the variable using .
, which is the PHP concat operator:
echo '<img class="img-vrienden" src="' . $row["prof_pic"] . '" /><br>' . $row["username"];
You'll need <input type="submit"
instead of <button>
.
This:
<button name="submit" type="submit" class="button">
Should be:
<input type="submit" name"submit">
Note: Your code is vulnerable to SQL Injection, it's better to escape the input using mysqli_real_escape_string
:
$name = mysqli_real_escape_string($server, $_POST['username']);
$waar = mysqli_real_escape_string($server, $_POST['omgeving']);
$sex = mysqli_real_escape_string($server, $_POST['geslacht']);
$status = mysqli_real_escape_string($server, $_POST['status']);
Upvotes: 2
Reputation: 3108
use "and" if you need all of conditions, not "or"
But better build sql where clause dynamic, testing isset parms like this:
$sql= "SELECT * FROM users WHERE 1=1";
if isset($_POST['username']) {
$name = $_POST['username'];
$sql .= " and username LIKE '%$name%'";
}
Upvotes: 1