php/mysql search function issue - php

I feel like I just need another set of eyes on this. There is of course something in the database to search, however nothing is displayed. Is there something wrong with the syntax or logic. This is all in one file index.php
<form action = "index.php" method = "post">
Search: <input type="text" name="value" placeholder="Is it part of the FWO?"></input>
<input type=submit name = "search" value="Search">
</form>
New Entry
<br>
<p>Search Results</p>
<hr />
<?php
error_reporting(E_ALL);
$title = $_POST['value'];
echo "You have searched: " .$title;
echo "<br>";
$con = mysql_connect("localhost", "user", "pass") or die ('Could not connect, this is the error: ' . mysql_error());
mysql_select_db("db") or die ('Sorry could not access database at this time. This is the error: ' . mysql_error());
$clean = msql_real_escape_string($_GET['value']);
echo "Another test ". $clean;
$run = mysql_query("SELECT * FROM db WHERE name = '$clean'") or die(mysql_error());
if(mysql_num_rows($run) >= 1){
echo "found entry";
while($i = mysql_fetch_array($run)){
echo $i['creator'];
}
}
else {
echo "No entries found";
}
mysql_close($con);
?>
</body>
</html>

Your form is using post method and you are trying get a value by $_GET
instead of this:
$clean = msql_real_escape_string($_GET['value']);
Use this:
$clean = msql_real_escape_string($_POST['value']);
Or
$clean = msql_real_escape_string($title);

To search inside mysql you should use LIKE. and if you want to search anywhere in the string you should encapsulate with %. for example:
$run = mysql_query("SELECT * FROM db WHERE name LIKE '%$clean%'") or die(mysql_error());
for more info: http://dev.mysql.com/doc/refman/5.7/en/string-comparison-functions.html

Related

PHP - Create check box by using the records from MySQL datebase as values

i am a newbie in php programming and i cant figure out where i have gone wrong as my php code wont execute.
As the title says i am trying to create check boxes in my site however the values will come from the mysql database.
I have a table named “campus” in MySQL database and it has 2 coloumns called id and room.
database
[![Database][1]][1]
http://i.imgur.com/uLP6niJ.png
current output
[![Current Output][2]][2]
http://i.imgur.com/cSOYPme.png
below is my code:
<?PHP
$hostname = "localhost";
$username = "root";
$password = "root";
$databaseName = "my computer";
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<html>
<body>
<form name="aform">
Choose a room:
<?php
$s = '';
$j = 0;
if ($q = $connect->query("SELECT * FROM `campus`")) {
while ($line = $q->fetch_assoc()) {
$s.= '<input type="checkbox" name="car'.$j.'" value="'.$line['room'].'">';
}
}
echo $s;
?>
</form>
</body>
</html>
You're not closing the while loop properly. Close the while loop as follow.
<?php
$sql = "SELECT room FROM campus";
$result = mysqli_query($sql);
while ($line = mysqli_fetch_array($result, MYSQL_ASSOC)) {
?>
<input type="checkbox" name="car" value="<?php echo $line['room']?>" />
<?php
}
?>
Welcome to PHP!
An error is that you're missing the semicolon that's needed after any php function (such as echo)
<?php echo $line['room']; ?>
And there's the missing PHP tags around the closing }
A third error is that you're not telling mysqli which connection to run the query on it should have:
mysqli_query($dbCon, $sql);
Apart from that it looks good, personally I prefer to use a PDO connection but mysqli is still good, but there are a few formatting tricks that can help prevent problems.
For example it's always a good idea to use back-ticks (`)
So:
$sql = "SELECT `room` FROM `campus`";
However, for this it might be best to use the * query. Which selects everything from the column so:
$sql = "SELECT * FROM `campus`";
The reason is how you're getting the data, you're telling PHP to create an array using the results.. but you've only given it one piece of data for each row. So if you give it all of the data it just makes it a little easier to use.
Here's the full code:
<?php $dbCon = mysqli_connect("localhost", "root", "root", "my computer");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}?>
<html>
<body>
<form name="aform">
Choose a room:
<?php
$sql = "SELECT * FROM `campus`";
$result = mysqli_query($dbCon, $sql);
while ($line = mysqli_fetch_array($result, MYSQL_ASSOC)) { ?>
<input type="checkbox" name="car" value="<?php echo $line['room']; ?>"
<?php } ?>
</form>
</body>
</html>
Also, if you're interested, here's how it'd be done in PDO:
<?php
try{
$con = new \PDO("mysql:host=" . 'localhost' . ";dbname=" . 'My Computer', 'root', 'root');
}catch(PDOException $e){
echo "Connection Failed";
die();
} ?>
<html>
<body>
<form name="aform">
Choose a room:
<?php
$result = $con->prepare("SELECT * FROM `campus`")
$result->execute();
while ($row = $result->fetch()) { ?>
<input type="checkbox" name="car" value="<?php echo $row['room']; ?>"
<?php } ?>
</form>
</body>
</html>
Still not working? Feel free to comment and I'll see what's up :)
Thanks,
P110
Try with this
<?php
$sql = "SELECT room FROM campus";
$result = mysqli_query($sql);
$campusArray = mysqli_fetch_array($result, MYSQLI_ASSOC);
foreach ($campusArray as $campus): ?>
<input type="checkbox" name="car" value="<?php echo $campus['room'];?>" />
<?php endforeach; ?>
I hope with this you can solve your problem.
alternative syntax is excellent for improving legibility (for both PHP
and HTML!) in situations where you have a mix of them.
http://ca3.php.net/manual/en/control-structures.alternative-syntax.php

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);
}
?>

Transferring MySQL server to php page = query not working?

I was trying to make a php page that would display a MySQL search engine, and itworked on one server: however, on that server crashed and I was forced to reboot it. Even when I'm using the same code, the search engine no longer works - my code is as follows:
<html>
<head>
<meta charset="UTF-8">
<title>Search Engine Test</title>
<h1>Gromax</h1>
</head>
<body>
<form action="search1.php" method="post">
<input type="text" name="keyword">
<input type="submit" name="search" value="Search">
<br>
<br>
</form>
<script language="php">
// Create a database connection
error_reporting(0);
$connection = mysql_connect("localhost", "$ mysql -u anonymous", "");
if (!$connection) {
die("Please reload page. Database connection failed: " . mysql_error());
}
// Select a databse to use
$db_select = mysql_select_db("test", $connection);
if (!$db_select) {
die("Please reload page. Database selection failed: " . mysql_error());
}
// Search Engine
// Only execute when button is pressed
if (isset($_POST['keyword'])) {
// Filter
$keyword = trim($_POST['keyword']);
// Select statement
$search = "SELECT Price FROM table_1 WHERE Model = '$keyword'";
// Display
$result = mysql_query($search) or die('query did not work');
while ($result_array = mysql_fetch_array($result)) {
$arrlength=count($result_array);
for($x=0;$x+1<$arrlength;$x++){
echo "Price: " . $result_array[$x];
echo "<br>";
}
}
}
?>
</script>
</body>
</html>
Any help would be appreciated.
I'm pretty sure you have an error in your query or your Database connection. Try commenting the line:
// error_reporting(0);
and see what error you get...
Try to use a format like this to determine what is going wrong in your select query:
<?php
$sql = "
SELECT
Price
FROM
table_1
WHERE
Model = '".$keyword."'
";
if(!$res = mysql_query($sql))
{
trigger_error(mysql_error().'<br />In query: '.$sql);
}
elseif(mysql_num_rows($res) == 0)
{
echo 'Geen resultaten gevonden';
}
else
{
while($row = mysql_fetch_assoc($res))
{
echo $row['voornaam'].'<br />';
}
}
?>

html form with select box cannot get value in another php page

i have a php page called page1.php with this form
<form id="myForm" action="page2.php" method="post">
<label for="name">a label:</label><input type="submit" name="SubmitCar" value="Done" id="fbutton" /> <br />
<br />
<select name="selectCar">
<?php
session_start();
$user = "cardatabase";
$password = "";
$host = "";
$database = "my_cardatabase";
$connessione = mysql_connect($host, $user, $password) or die( mysql_error() . " <br/> could not connect to server");
mysql_select_db($database, $connessione) or die( mysql_error() . " <br/> could not connect datbase");
$id = $_SESSION['myid'];
$query = "select IDCar
from Car";
$result = mysql_query($query, $connessione) or die(mysql_error());
if( mysql_num_rows($result) > 0 ) {
$array = array();
$i = 0;
while ($row = mysql_fetch_array($result)) {
$array[$i] = $row['IDCar'];
++$i;
}
for ($i = 0; $i < count($array); ++$i) {
echo "<option value='$array[$i]'>$array[$i]</option>";
}
}
mysql_close();
?>
</select>
</form>
Simply fill the select box from DB. Now here's the problem. When i reach page2.php i need the value of the select box and i tried this
page2.php
<?php
$value = $_POST['selectCar'];
?>
But it's not working, so i tried to use sessions in this way
page1.php
</form>
<?php
if(isset($_POST['SubmitCar'])){
$_SESSION['idAuto'] = $_POST['selectCar'];
}
?>
out of the form, but still not working. What can i do to get this value in page2.php??
Try using this code to build your <option> , and use mysqli when working with the database
$result = mysqli_query($connessione, $query) or die(mysql_error());
if( mysqli_num_rows($result) > 0 ) {
$i=0;
while ($row = mysqli_fetch_row$result)) {
echo "<option value='".$row[$i]."'>".$row[$i]."</option>";
$i++;
}
}
Also, it's not indicated to have mysql tables with names in uppercase, or fields with names in uppercase.
Page2.php
You forgot to echo it.
<?php
$value = $_POST['selectCar'];
echo $value;
?>
I found a simple workaround for my problem. It might not be perfect but it works.
i deleted the action="page2.php" in the form of page1
in page1.php add this code outside the form
This will do the trick
if(isset($_POST['SubmitCar'])){
$_SESSION['idCar'] = $_POST['selectCar'];
header('Location:page2.php');
}

Simple php/sql search engine

I am trying to make a simple php, sql search engine that will select everything from my database that is "LIKE" the keyword (query) and display it. However it will not work. It only displays the text "problem"(see line 32) and after hours of troubleshooting I still can not figure this out.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Search Engine Test</title>
</head>
<body>
<script language="php">
// Create a database connection
$connection = mysql_connect("*****","*****","*****");
if (!connection) {
die ("Please reload page. Database connection failed: " . mysql_error());
}
// Select a databse to use
$db_select = mysql_select_db("*****",$connection);
if (!$db_select) {
die("Please reload page. Database selection failed: " . mysql_error());
}
// Search Engine
// Only execute when button is pressed
if (isset($_POST['search'])) {
// Filter
//$keyword = trim ($keyword);
echo $keyword;
// Select statement
$search = mysql_query("SELECT * FROM tbl_name WHERE cause_name LIKE '%keyword%'");
// Display
$result = #mysql_query($search);
if (!$result){
echo "problem";
exit();
}
while($result = mysql_fetch_array( $search ))
{
echo $result['cause_name'];
echo " ";
echo "<br>";
echo "<br>";
}
$anymatches=mysql_num_rows($search);
if ($anymatches == 0)
{
echo "Nothing was found that matched your query.<br><br>";
}
}
</script>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<input type="text" name="keyword">
<input type="submit" name="search" value="Search">
</body>
</html>
Try and change:
if (isset($_POST['search'])) { //$_POST['search'] just tells that there are a submit-button when submitting (and the name of it)
// Filter
//$keyword = trim ($keyword);
echo $keyword; //You're echoing out value of $keyword which hasn't been set/assigned
// Select statement
//You're always searching for the word keyword with leading and/or trailing characters
//You're not searching for a dynamically assigned value which I think is what you want
$search = mysql_query("SELECT * FROM tbl_name WHERE cause_name LIKE '%keyword%'");
//You're executing an already defined query (assigned in $search)
$result = #mysql_query($search); //You're suppressing errors, it's bad practice.
if (!$result){
echo "problem";
exit();
}
to:
if (isset($_POST['keyword'])) {
// Filter
$keyword = trim ($_POST['keyword']);
// Select statement
$search = "SELECT * FROM tbl_name WHERE cause_name LIKE '%$keyword%'";
// Display
$result = mysql_query($search) or die('query did not work');
IMPORTANT!
<script language="php"> isn't valid. You should type <?php at the beginning of php-code and ?> to end php-code.
UPDATE:
You will also have to change this code:
while($result = mysql_fetch_array( $search ))
{
echo $result['cause_name'];
echo " ";
echo "<br>";
echo "<br>";
}
$anymatches=mysql_num_rows($search);
if ($anymatches == 0)
{
echo "Nothing was found that matched your query.<br><br>";
}
}
TO:
while($result_arr = mysql_fetch_array( $result ))
{
echo $result_arr['cause_name'];
echo " ";
echo "<br>";
echo "<br>";
}
$anymatches=mysql_num_rows($result);
if ($anymatches == 0)
{
echo "Nothing was found that matched your query.<br><br>";
}
}
When making new code, you really should NOT use mysql_ functions*, because they're deprecated. Look into PDO or mysqli instead.
Expanding your code, we can see that:
$result = #mysql_query($search);
turns into:
$result = #mysql_query(mysql_query("SELECT * FROM tbl_name WHERE cause_name LIKE '%keyword%'"));
Which doesn't make much sense.
Change the first line to:
$search = "SELECT * FROM tbl_name WHERE cause_name LIKE '%keyword%'"
or, instead of assigning $search a value at all, just skip to assigning $result the value that $search currently has.
EDIT: to help you explain:
Change this:
$search = mysql_query("SELECT * FROM tbl_name WHERE cause_name LIKE '%keyword%'");
// Display
$result = #mysql_query($search);
if (!$result){
echo "problem";
exit();
}
to this:
$result = mysql_query("SELECT * FROM tbl_name WHERE cause_name LIKE '%keyword%'");
// Display
if (!$result){
echo "problem";
exit();
}

Categories