Search function with php - php

I've got my code which is searching my database and table for a certain condition but when I search it doesn't return any result. I've looked at a few tutorials and cant find the issue. Any help is appreciated. I know the code is outdated and I should be using mysqli. I will be changing this when the issue is rectified.
<?php
$output = NULL;
if(isset($_POST['submit'])){
mysql_connect("localhost", "root", "") or die (mysql_error());
mysql_select_db("first_db") or die("can not connect");
$search = $mysql->real_escape_string($_POST['search']);
$resultSet = $mysql->query("SELECT * FROM voulunteer WHERE Name LIKE '%search%'");
if($resultSet->num_rows > 0){
while($rows = $resultSet->fetch_assoc())
{
$StaffStatus = $rows['StaffStatus'];
$name = $rows['Name'];
$output = "Staff Status: $StaffStatus<br/>name: $Name<br/><br/>";
}
}else{
$output = "No results";
}
}
?>
<form method-"POST">
<input type="TEXT" name"search" />
<input type="SUBMIT" name="submit" value="Search" />
</form>

Your query is written wrong
instead of
$resultSet = $mysql->query("SELECT * FROM voulunteer WHERE Name = LIKE '%search&'");
try this
$resultSet = $mysql->query("SELECT * FROM voulunteer WHERE Name LIKE '%search%'");
edit: added nogad's comment about changing the & to %

Try the query in phpmyadmin first. If there's an error in the query it will tell you

Related

Advanced SQL statement executing checkbox checked

I have HTML code with checkbox and submit button as below
<form action="checkboxes.php" method="post">
<input type="checkbox" name="checkbox1" value="Yes">4K</input>
<input type="submit" name="formSubmit" value="Submit" ></input>
</form>
And in my PHP I have a file "config.php" that his function is to connect to my database:
<?php
/* Database connection */
$sDbHost = 'localhost';
$sDbName = 'testowanie';
$sDbUser = 'root';
$sDbPwd = '';
$dbcon = mysqli_connect ($sDbHost, $sDbUser, $sDbPwd, $sDbName);
?>
And a second PHP file:
<?php
include('config.php');
$sqlget = "SELECT * FROM monitory";
$sqldata = mysqli_query($dbcon, $sqlget)or die("Can't connect to the database");
if(isset($_POST['checkbox1']) &&
$_POST['checkbox1'] == 'Yes')
{
while($row = mysqli_fetch_array($sqldata, MYSQLI_ASSOC)) {
echo '.';
echo $row['cena'];
}
}
?>
This all three connected files each others do that if the checkbox is checked this SQL statement are executed: SELECT cena FROM monitory; but I want to execute this statement "SELECT * FROM monitory WHERE cena=1000;
I tried to do this like around 2 hours but I really don't know how to do this.
So You want to choose one of two different queries according to input conditions. Then do it so :-)
<?php
include('config.php');
if (isset($_POST['checkbox1']))
$sqlget = "SELECT * FROM monitory WHERE cena = 1000";
else
$sqlget = "SELECT * FROM monitory";
$sqldata = mysqli_query($dbcon, $sqlget)or die("Can't connect to the database");
while($row = mysqli_fetch_array($sqldata, MYSQLI_ASSOC)) {
echo '.';
echo $row['cena'];
}

How to catch empty query in php

I have several articles in my db and search on my site. if the user does not enter anything and click search, then displays all articles. How to catch empty request?
Code:
<?php
mysql_connect("localhost", "user", "password") or die("Error");
mysql_select_db("selv_hram") or die("Error");
mysql_query('SET names "utf8"');
if (isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = htmlspecialchars($searchq);
$query = mysql_query("SELECT * FROM articles WHERE title LIKE '%$searchq%' OR text_article LIKE '%$searchq%'");
$count = mysql_num_rows($query);
$output = '';
if ($count == 0) {
$output = 'Nothing find';
}else {
while ($row = mysql_fetch_array($query)) {
$title = $row['title'];
$text = $row['text_article'];
$id = $row['id'];
$output .= '<div>'.$title.' '.$text.'</div>';
}
}
}
?>
<div class="content-article">
<form name="search" action="index.php" method="post" class="search-form">
<input type="text" name="search" placeholder="search" />
<input type="submit" value=">>">
<?php print("$output"); ?>
</div>
After you read this post about SQL-injection,
change
if (isset($_POST['search'])) {
to
if (!empty($_POST['search'])) {
This is simple validation.
if(empty($_POST['search'])) {
echo "Empty search query";
} else {
//search query
}
Check the user input first, if it is empty change the query. like below
$searchq = htmlspecialchars($searchq);
if(trim($searchq) == ''){
$query = mysql_query("SELECT * FROM articles");
}else{
$query = mysql_query("SELECT * FROM articles WHERE title LIKE '%$searchq%' OR text_article LIKE '%$searchq%'");
}
Dont use depreciated mysql_ functions. Go for mysqli

Why can't I call random number from the database?

I am having a problem calling random number from the database.
Here is the my link:
<form method="post" action="pages/test.php?id=<?php echo "$id[0]";?>&ran=<?php echo "$ran";?>">
<input type="submit" name="Submit" value="Click here" class="button">
</form>
And here is my second page code:
<?php
if (!isset($submit)) {
//database connection here
$id = $_GET['id'];
$ran = $_GET['ran'];
$query2 = "SELECT * FROM table WHERE id='$id' AND ran='$ran'";
$result2 = mysql_query ($query2) or die ('Could not run query: ' . mysql_error());
$info = mysql_fetch_array ($result2);
?>
When I call for example firstname or lastname it woks okay. But $ran is returning empty. Am I missing something.
Whilst I don't totally understand your request, one notable error I can see is below.
Your second page should be like this
<?php
if (isset($_POST)) {
//database connection here
$id = $_POST['id'];
$ran = $_POST['ran'];
$query2 = "SELECT * FROM table WHERE id='$id' AND ran='$ran'";
$result2 = mysql_query ($query2) or die ('Could not run query: ' . mysql_error());
$info = mysql_fetch_array ($result2);
}
?>

select from mysql table using array

i am trying display a the rows in my database table using the array of ids gotten from another table. i want it to display the first row which is $rowsfriend. and display the second row which is rows .......... but it only displays $rowsfriend
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ochat";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM friends where friend1='".($_POST[id])."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$rowsfriend = $row["friend2"];
echo $rows;
}
}
$sqll = "SELECT * FROM users WHERE id IN ($rowssfriend)";
$resultt = $conn->query($sqll);
if ($resultt->num_rows > 0) {
while($roww = $resultt->fetch_assoc()) {
$rowsss = $row["username"];
echo $rowss;
}
}
else {
?>
<h1>Register</h1>
<form action="selectfriends.php" method="post">
id:<br />
<input type="text" name="id" value="" />
<br /><br />
<input type="submit" value="enter" />
</form>
<?php
}
?>
Instead of two queries, you can write this nested query.
$sqll = "SELECT * FROM USERS WHERE ID IN (SELECT friend2 FROM friends WHERE friend1='".$_POST[$id]."')";
$resultt = $conn->query($sqll);
if ($resultt->num_rows > 0)
{
while($roww = $resultt->fetch_assoc())
{
$rowsss = $row["username"];
echo $rowss;
}
}
Hope this solve your problem .
Please try this version of code instead, if you might:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ochat";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT users.* FROM users WHERE users.id IN (SELECT friend2 FROM friends where friend1='".($_POST[id])."')";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$rows = $row["username"];
echo $rows;
}
}
else {
?>
<h1>Register</h1>
<form action="selectfriends.php" method="post">
id:<br />
<input type="text" name="id" value="" />
<br /><br />
<input type="submit" value="enter" />
</form>
<?php
}
?>
As far as I understood the code well, the problem was with the variable name typo as #Admieus wrote but also in the fact that in each iteration of the first loop variable $rowsfriend got overriden with a new value so after the end of the loop, $rowsfriend contained the last id from the result of the first query $sql.
The above version makes only one query using subquery in it to get directly usernames who are friends of friend1 given in $_POST[$id].
I hope it helps.
There are typos in the second loop.
You assign the value to $rowsss and try to echo from $rowss notice the difference.
Also, you assign the fetch_assoc result to $roww and then try to call it again with $row.
$sqll = "SELECT * FROM users WHERE id IN ($rowsfriend)";
$resultt = $conn->query($sqll);
if ($resultt->num_rows > 0) {
while($roww = $resultt->fetch_assoc()) {
$rowsss = $roww["username"];
echo $rowsss;
}
}
Point of improvement is: check your variable names, make names that are easy to understand and hard to mix up.
For instance, the variable containing the sql query should not be named $sql and to make it worse a second query shoul not be named sqll. Instead use names that imply what you are doing.
$querySelectFriendsFrom = "SELECT * FROM users WHERE id IN ($friendId)";
Don't take this as a hard rule, it's more of a tip to prevent silly mistakes.
Update: there was also a type in the query referring to rowssfriend instead of rowsfriend. Fixed above.

clickable results in php

Trying to display results that are clickable.
<form method="post" action="AF9.php">
<input type="submit" name="submit" value=" search ">
<input type="text" name="search" />
</form>
and here is partially the AF9.php file:
<?php
$connection = #new mysqli(HOSTNAME, MYSQLUSER, MYSQLPASS, MYSQLDB);
if ($connection->connect_error) {
die('Connect Error: ' . $connection->connect_error);
}
else {
$search=$_POST["search"];
$query="SELECT *, FROM comments AS c JOIN namestable2 AS w ON c.w1 = w.w1
WHERE name like '%$search%'
ORDER BY name DESC";
$connection->query("SET NAMES utf8");
$result_obj = '';
$result_obj = $connection->query($query);
while($result = $result_obj->fetch_array(MYSQLI_ASSOC)) {
$items[] = $result;
}
foreach ($items as $item) {
echo(''.$item['word'].'');
}?>
however when I click on the result, it says "Undefined index: search". Please help
Hardcoded links that end with "?key=value" like "?search=xyz" will pass via the GET stream, not the POST. Try changing this:
$search=$_POST["search"];
to this:
$search=$_GET["search"];
Are you sure you meant to do $search=$_POST["search"];?
If you're sending it in the URL, you'll need to do $search=$_GET["search"]; instead.
Your link is a $_GET not $_POST change
$search=$_POST["search"];
to
$search = $_GET['search'];

Categories