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 />';
}
}
?>
Related
I am trying to set the value to be displayed in a SELECT list using php scripts.
What I have done is create an input html page (MatchSelect.php) which shows two select boxes and a submit button.
On pressing the submit button a new new php file is called (MatchSelectResult.php) which is as follows;
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Seniors Inter-Club Match Management</title>
<link rel="stylesheet" href="MainBody.css">
<link href="dropDown.css?v=1.1" rel="stylesheet" >
<?PHP require '../../configure.php';
include "Main_PHP_Code.php" ;
?>
</head>
<body>
<?PHP include "MatchPopulate.php"; ?>
<div class="container">
<?PHP include "menu.txt" ?>
<div class="content">
<div>
<h1>Team Selection</h1>
<form name="matchSelect" method="POST" action="MatchUpdate.php">
<p>
<select id = "Venue" name= "Venue" >
<option disabled selected value> -- select an option -- </option>
<option value="Away">Away</option>
<option value="Home">Home</option>
</select>
match against
<select id ="Opponents" name ="Opponents">
<?php
Global $OpponentName;
$oop = $OpponentName;
opponent_load('$oop');
?>
</select>
etc.
the function opponent_load() is contained within the "Main_PHP_Code.php" code and is as follows;
function opponent_load($oppon){
Global $OpponentName;
$db_handle = mysqli_connect(DB_SERVER, DB_USER, DB_PASS );
$database = "matchmanagementdb";
$db_found = mysqli_select_db($db_handle, $database);
if ($db_found) {
$SQL = "SELECT * FROM opponentsdb";
$result = mysqli_query($db_handle, $SQL);
while ( $db_field = mysqli_fetch_assoc($result) ) {
$uName = $db_field['Opponents'];
if ($uName == $oppon)
{
$selected = 'selected="selected"';
}
else
{
$selected = '';
}
echo "<option value='$uName' $selected> $uName </option>";
}
}
else {
print "Database NOT Found ";
}
mysqli_close($db_handle);
}
The "MatchPopulate.php" code in the HEAD section is used to search the mySQL database using the two values from MatchSelect.php page. If the data is found, then the global variable $OpponentName is defined. The code is thus;
<?php
Global $OpponentName;
//require '../../configure.php';
$uOpponentName = $_POST['Opponents'];
$uVenue = $_POST['Venue'];
//$db_handle = mysqli_connect(DB_SERVER, DB_USER, DB_PASS );
$database = "matchmanagementdb";
$conn = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// check to see if Match (Opponents + Venue)already in the database, if so, retrieve data or add match to database
$SQL = "SELECT * FROM teamselect WHERE Opponents = '$uOpponentName' AND Venue = '$uVenue'";
$result = $conn->query($SQL);
//if $result->num_rows >0 then retrieve data ELSE add match to database
if (!$result){
print "Error selecting record: " . $sql . "<br>" . $conn->error;
} else {
if ($result->num_rows >0) {
while($row = $result->fetch_assoc()) {
$OpponentName = $row['Opponents'];
}
} else {
$sql = "INSERT INTO teamselect (Opponents, Venue) VALUES ('$uOpponentName', '$uVenue')";
if ($conn->query($sql) === TRUE) {
} else {
print "Error adding record: " . $sql . "<br>" . $conn->error;
}
}
}
$conn->close();
?>
The code stops when it tries to populate the Opponents Select box on MatchSelectResult.php. Any help to solve this would be appreciated.
I have solved the problem by opening a session and using $_SESSION["Opponents"] to pass the variable around the scripts.
Also changed opponent_load('$oop') to opponent_load($oop).
I'm making a web application, and I'm having trouble figuring out how to stop the PHP from making a query to my database every time the page is reloaded.
Basically when the form is submitted I want the PHP to make a query to the database adding the variables, however, because it has saved those values in the $_POST, it's making a query every time I refresh with those same values.
I want it to make the query, then perhaps unset the $_POST values or something so that it doesn't satisfy the if condition, and in turn stops it from querying the database with repeat values when the submit button hasn't updated them with new values.
Sorry if that's convoluted I'm trying to explain my problem the best I can.
Here is the PHP
<?php
//Require login gile -- Fatal error if not found
require_once('login.php');
require_once('app.html');
//Connect w/ MySQL database [login variables]
$con = new mysqli($hn, $un, $pw, $db);
//If connection error -> kill application and display error
if ($con->connect_error) die('Connect Error (' . $con->connect_errno . ') '. $con->connect_error);
//If both goal and difficulty are set
if (!empty($_POST['goal']) && !empty($_POST['difficulty'])) {
$goal = get_post($con, 'goal');
$difficulty = get_post($con, 'difficulty');
$query = "INSERT INTO items VALUES" . "('$goal', 1, '$difficulty', NULL)";
$result = $con->query($query);
if(!$result) echo "INSERT failed: $query<br>" . $con->error . "<br><br>";
}
unset($_POST['goal']);
unset($_POST['difficulty']);
//close connection
$con->close();
function get_post($conn, $var) {
return $conn->real_escape_string($_POST[$var]);
}
?>
html
<!DOCTYPE html>
<html>
<head>
<title>Testing</title>
<!--Page Style-->
<link type="text/css" rel="stylesheet" href="Style.css">
<!--jQuery-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<!--RateYo | http://prrashi.github.io/rateYo/-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/rateYo/2.0.1/jquery.rateyo.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/rateYo/2.0.1/jquery.rateyo.min.js"></script>
</head>
<body>
<div id="parent1">
<form id="goalForm" method="post" action="PHP.php">
<!--Goal Value-->
<input id="goalName" type="text" name="goal" maxlength="150" placeholder="Type your goal here!">
<!--Star Rating-->
<div id="rateYo"></div><br>
<!--Value from stars to be submitted-->
<input id="dif" type="hidden" name="difficulty">
<input class="but1" id="firstSubmit" type="button" value="Submit">
<input class="but1" id="submitton" type="submit" style="display:none" value="Difficulty?">
</form>
</div>
<script>
$("#goalName").val("");
//First Submit Onclick
$("#firstSubmit").click(function() {
if($("#goalName").val() == "") {
alert("Please insert a value.");
}
else {
$("#goalName").fadeOut("slow" , function() {
$("#rateYo").rateYo({
numStars: 10,
rating: 0,
fullStar: true,
starWidth: "70px",
ratedFill: "#E74C3C",
maxValue: 10
});
$("#rateYo").fadeIn("slow");
});
$(this).hide();
$("#submitton").show();
}
});
//Star Submit
$("#goalForm").submit(function() {
var $rateYo = $("#rateYo").rateYo();
var rating = $rateYo.rateYo("rating");
if($("#goalName").val() == "") {
alert("Please insert a value.");
return false;
}
else if(rating == 0) {
alert("Please set a difficulty level.");
return false;
}
else {
$("#dif").val(rating);
}
});
</script>
Try it plz
<?php
//Require login gile -- Fatal error if not found
require_once('login.php');
require_once('app.html');
//Connect w/ MySQL database [login variables]
$con = new mysqli($hn, $un, $pw, $db);
//If connection error -> kill application and display error
if ($con->connect_error) die('Connect Error (' . $con->connect_errno . ') '. $con->connect_error);
//If both goal and difficulty are set
if (!empty($_POST['goal']) && !empty($_POST['difficulty'])) {
$goal = get_post($con, 'goal');
$difficulty = get_post($con, 'difficulty');
$query = "INSERT INTO items VALUES" . "('$goal', 1, '$difficulty', NULL)";
$result = $con->query($query);
if(!$result) echo "INSERT failed: $query<br>" . $con->error . "<br><br>";
//You can write samepage name in location as window.location='abc.php'
echo "<script>window.location=''</script>";
}
//close connection
$con->close();
function get_post($conn, $var) {
return $conn->real_escape_string($_POST[$var]);
}
?>
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
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();
}
I've created a webpage which uses JQuery to redirect the content of a form to another webpage using PHP to connect to a database to find some content and put it back on the first page.
Eveything works great (thanks to the help of followers of stack overflow :-) ) but now I'd like the following : I'm asking for the postal code of a city, if I'm lucky this postal code is unique (only one city has it) but it also happens that a postal code is the same for several cities so I'd like in that case to display a listbox for the user to choose his/her city.
Does someone has an idea of how to do this ?
my code :
home.html
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form action="/" id="myform">
<input type="text" name="postal_code" id="postal_code" placeholder="Search..." />
<input type="submit" value="Search" />
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>
<script>
$('#myform').submit(function() {
var url = 'target.php';
var postal_code = $('#postal_code').val();
$.post( url, { postal_code: postal_code },
function( data ) {
$( "#result" ).empty().append( data );
}
);
return false;
});
target.php
<?php
try
{
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$bdd = new PDO('mysql:host=localhost;dbname=mydatabase', 'root', '', $pdo_options);
$response = $bdd->prepare('SELECT city FROM city_list where postal_code = ?');
$response->execute(array($_POST['postal_code']));
echo '<ul>';
while ($data = $response->fetch())
{
?>
<br/>The city you entered the postal code is : <?php echo $data['city'];
}
$response->closeCursor();
}
catch (Exception $e)
{
die('Error : ' . $e->getMessage());
}
?>
EDIT:
This is the code ok for my needs. I'd only to make some very minor changes from Jules' code to make it ok (for an unknow reason his answer worked perfectly for him but not for me :-) )
<?php
try {
//Get the postal code:
$postcode = $_POST['code_postal'];
//Make MySQL connection
mysql_connect("localhost", "root", "") or die (mysql_error());
//Select the database
mysql_select_db("site_artisans_amélioré");
//Do your query based on the postcode...
$query = "SELECT ville FROM liste_communes_code_postaux where code_postal = '" . mysql_real_escape_string($postcode) . "'";
//Return the response in a variable
$data = mysql_query($query) or die (mysql_error());
//echo "Num rows: " . mysql_num_rows($data);
//Check how many rows the query returned. If more than 1 that means several cities
//exist for one postcode, so you should show a listbox.
//If not, just return the ville name
if (mysql_num_rows($data) > 1) { ?>
<select name="cities">
<?php while ($row = mysql_fetch_assoc($data)) { ?>
<option value="<?php echo $row['ville']?>"><?php echo $row['ville']?></option>
<?php } ?>
</select>
<?php }
else {
$row = mysql_fetch_assoc($data);
echo $row['ville'];
}
}
catch (Exception $e) {
die("Error : " . $e->getMessage());
}
?>
I am not sure which library you are using for your Database queries, so I'll do it in Pseudo-code and mysql_query..
target.php
<?php
try {
//Get the postal code:
$postcode = $_POST['postal_code'];
//Make MySQL connection
mysql_connect("localhost", "username", "password") or die (mysql_error());
//Select the database
mysql_select_db("mydatabase");
//Do your query based on the postcode...
$query = "SELECT city FROM city_list where postal_code = '" . mysql_real_escape_string($postcode) . "'";
//Return the response in a variable
$data = mysql_query($query);
//Check how many rows the query returned. If more than 1 that means several cities
//exist for one postcode, so you should show a listbox.
//If not, just return the city name
if (mysql_num_rows($data) > 1) { ?>
<select name="cities" multiple="multiple">
<? while ($row = mysql_fetch_assoc($data)) { ?>
<option value="<?=$row['city']?>"><?=$row['city']?></option>
<? } ?>
</select>
<? }
else {
$row = mysql_fetch_assoc($data);
echo $row['city'];
}
}
catch (Exception $e) {
die("Error : " . $e->getMessage());
}
?>
I hope you catch my drift and you can complete it yourself.