I'm trying to create a search engine that will pull out information from a mySQL database. My code is as follows:
<!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("localhost", "root", "", "test");
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 * LIKE '%$keyword%'";
// Display
$result = mysql_query($search) or die('query did not work');
while ($result_arr = mysql_fetch_array($result)) {
echo $result_arr['*'];
echo " ";
echo "<br>";
echo "<br>";
}
$anymatches = mysql_num_rows($result);
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">
However, when I run it, I receive a notification saying that I've been forbidden to access the server. Any help would be appreciated.
$search = "SELECT Price FROM table_1 WHERE fieldname LIKE '%$keyword%'";
You can't use single quotes around a field name, as that's how strings are defined. You can use the grave key (`) if your table name is a reserved word. You also can't do WHERE *, you need to specify a field to compare the keyword to.
I would also recommend not using the mysql commands in PHP as they are deprecated. Use the more recent mysqli commands
Related
Okay this is abit hard to explain but I currently have a website where I'm using PHP and MySQL to pull tables into the web pages and display them. I've been able to make a search function to look for specific values in the table. I'll show you my code.
<!DOCTYPE php>
<html>
<head>
<link rel="stylesheet" href="style.php" media="screen">
</head>
<body>
<a id="TableButton" href="/Test.php">Items Table</a>
<a id="Clear" href="index.php">Clear Search</a>
<center>
<form method="GET" id="SearchPerson">
<select name="Drop" id="Select">
<option value="FirstName">First Name</option>
<option value="Surname">Surname</option>
<option value="MobileNumber">Mobile Number</option>
<option value="Code">Code</option>
<option value="TeamGroup">Team Group</option>
<option value="Home">Home</option>
</select>
<input type="text" name="Box">
<input type="submit" value="Search">
</form>
</center>
<?php
$host = "localhost";
$user = "root";
$pass = "password";
$db = "Database";
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
mysql_select_db($db) or die ("Unable to select database!");
if($_REQUEST['Drop']=='MobileNumber') {
$MobileNumber = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE MobileNumber = $MobileNumber";
}
elseif($_REQUEST['Drop']=='Code') {
$Code = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE Code = '$Code'";
}
elseif($_REQUEST['Drop']=='TeamGroup') {
$TeamGroup = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE TeamGroup = '$TeamGroup'";
}
elseif($_GET['Drop']=='FirstName') {
$FirstName = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE FirstName = '$FirstName'";
}
elseif($_GET['Drop']=='Surname') {
$Surname = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE Surname = '$Surname'";
}
elseif($_REQUEST['Drop']=='Home') {
$Home = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE Home = '$Home'";
}
else{
$query = "SELECT * FROM Person";
}
print "<center id=Title>Person Table</center>";
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($result);
print '<center><table><tr>';
foreach($row as $name => $value) {
print "<th>$name</th>";
}
print '</tr>';
while($row) {
print '<tr>';
foreach($row as $key=>$value) {
if($key=='MobileNumber'){print "<td><a href='/Test.php?MobileNumber=$value'>$value</a></td>";}
elseif($key=='TeamGroup'){print "<td><a href='/Test.php?TeamGroup=$value'>$value</a></td>";}
elseif($key=='Group'){print "<td><a href='/Test.php?Home=$value'>$value</a></td>";}
else{print "<td>$value</td>";}
}
print '</tr>';
$row = mysql_fetch_assoc($result);
}
print '</table></center>';
}
else {
echo "No People found!";
}
mysql_free_result($result);
mysql_close($connection);
?>
</body>
</html>
Problem is even though I've got the search working it only works if I have the full values whereas i want it so say that i put part of someone mobile number in then itll display the mobile numbers that have those parts of the value in it. For example say that a few people had a mobile number starting with 0783 and I type that into the search box I want it to show up all people with 0783 in their mobile number.
What you are looking for is "SELECT * FROM Person WHERE MobileNumber LIKE '%".$_POST['MobileNumber']."%'", which will look for any string that contains the string you want, but may also be longer on either side. For example, "foo" will return the rows with values "foobar", "barfoo", "barfoobar" and of course "foo", but not "fo".
The % is a wildcard here, which means that you can also do something like "SELECT * FROM Person WHERE MobileNumber LIKE '".$_POST['MobileNumber']."%'" if you specifically want to return rows with values starting with your string ("foobar", but not "barfoo" in our example above).
Please also note the " and '.
Also:
Don't use mysql_query. It's depreciated and will be removed in future versions of PHP. Use PDO or mysqli instead.
Your code is definitely not safe. At least use prepared statements to prevent injection. I would advise against using addslashes as it is very prone to resulting in double escapes if you are not paying attention, and as far as you may also want to go the magic_quotes, be aware it is not portable and may cause you trouble if you rely solely on this. Use mysql_real_escape_string instead, as it is very mysql-oriented and specific.
I'm creating this web page for this class that I'm in and for it I need to concatenate two separate HTML form inputs with a space in between and insert them into a MySQL database. Specifically I ask the user for their first name and their last name in separate HTML form inputs and I have to concatenate those two input into a full name with a space in between (or else "Bob" and "Ross" concatenated would be "BobRoss" instead of "Bob Ross"). I don't know where to start when doing that. Also I need to check that the full name isn't already in the database before inserting it into the database, but I'm already doing that with the first name and last name so that shouldn't be too hard.
Here is the HTML page with the form inputs:
<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>
<body>
<div id="main">
<h1>About</h1>
<form action="Insert.php" method="post">
<p>First name:</p><input type="text" name="firstname"><br>
<p>Last name:</p><input type="text" name="lastname"><br>
<p>Age:</p><input type="text" name="age"><br>
<input type="submit">
</form>
<?php include("Footer.php");?>
</div>
</body>
</html>
And here is the PHP page where it inputs the data into the database. Currently I'm inputing the user's first name, last name, and age, but I need to concatenate the first and last name and make sure it isn't in the database and then insert it into the database and I haven't done that. Currently I make sure that the first name is unique, I make sure that the last name is unique, but I don't care whether the age is unique or not.
<?php
$con = mysql_connect("localhost","a7068104_user2","wiseguy1345");
if(!$con) {
die("could not connect to localhost:" .mysql_error());
}
header("refresh:1.5; url=NamesAction.php");
mysql_select_db("a7068104_world") or die("Cannot connect to database");
$name = mysql_real_escape_string($_POST['firstname']);
$query = "SELECT * FROM names_1 WHERE firstname='$name'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "Your name is already in the database and will not be added again!";
}
else {
$query = "INSERT INTO names_1 (firstname) VALUES('$name')";
$result = mysql_query($query);
if($result) {
echo "Your first name was successfully added to the database!";
}
else{
echo "Your first name couldn't be added to the database!";
}
}
$name = mysql_real_escape_string($_POST['lastname']);
$query = "SELECT * FROM names_1 WHERE lastname='$name'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "Your name is already in the database and will not be added again!";
}
else {
$query = "INSERT INTO names_1 (lastname) VALUES('$name')";
$result = mysql_query($query);
if($result) {
echo "Your first name was successfully added to the database!";
}
else{
echo "Your first name couldn't be added to the database!";
}
}
$name = mysql_real_escape_string($_POST['age']);
$query = "INSERT INTO names_1 (age) VALUES('$name')";
$result = mysql_query($query);
if($result) {
echo "Your name was successfully added to the database!";
}
else {
echo "Your name couldn't be added to the database!";
}
mysql_close($con);
?>
<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>
<body>
<div id="main">
<h1>Names</h1>
<p>You will be redirected back to the <b>Names</b> page in a moment.</p>
<?php include("Footer.php");?>
</div>
</body>
</html>
For a start you shouldn't be using mysql functions as this extension
is deprecated as of PHP 5.5.0, and will be removed in the future.
I suggest using the new improved PDO library and PDO Prepared Statements, see here.
As for the concatenation, you could simply do it like this:
$concatenated_name = $_POST['firstname'] . " " . $_POST['lastname'];
This would concatenate the names with a space in between.
You can then use $concatenated_name in your queries.
However I still strongly recommend you use PDO for all your functions.
$fullname = trim($_REQUEST['firstname']).trim($_REQUEST['lastname']);
Alrighty, so i'm quite a beginner when it comes to PHP and MySQL programming so the problem might be quite noobish but anyway here's my situation. I've got a content page with a dropdown menu that should give me a $_POST value (the options are taken from a database column): here's the code for that
<link href="../css/pagestyle.css" rel="stylesheet" type="text/css" />
<?php
include("../panel/config.php");
$db = mysqli_connect($server, $username, $password, $database);
if(mysqli_connect_errno()) { //if connection database fails
echo("Connection not established " .
mysqli_connect_error($db) . "</p>");
}
$query = "SELECT username FROM users WHERE email = '1' ORDER BY username ASC";
$result = mysqli_query($db,$query);
if (!$result) {
echo("Error, the query could not be executed: " .
mysqli_error($db) . "</p>");
mysqli_close($db);
}
echo "
<form action='myscript' method='post'>
<select name='test'>
<option value = 'none' selected = 'selected' >
`Select a DJ:` </option>";
while ($row = mysqli_fetch_assoc($result)){
echo '<option value="' . $row['username'] . '">' . $row['username']. '</option>';
}
echo"
<input type='submit' value='submit' name='submit'>
</select>
</form> ";
?>
Quite a bit of code for such a small function i know. Anyway the drop down menu gets its options from a database column and that works fine, now when i press the submit button, it runs another php page that's coded like this:
<link href="../css/pagestyle.css" rel="stylesheet" type="text/css" /><html>
<?php
include("../panel/config.php");
$con = mysqli_connect($server, $username, $password, $database);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_POST['test'];
$order = "UPDATE `habboxli_system`.`users` SET `points` = points+1 WHERE `users`.`username` ='$id'";
mysql_query($order);
echo "name is $id";
mysqli_close($con);
echo "Vote posted!";
?>
This code should take the value that was chosen in the drop down menu and use it to update a specific cell in the database, i signed it to a variable called $id just for testing purposes but the value seems to be blank, so from that i presume that the drop down menu didn't return a value when it navigated from the original page (www.mywebsite.com/#/option.php) to the myscript.php page (www.mywebsite.com/#/myscript.php). Any help on how to get this to work would be much appreciated.
As was said in the comments, you are using the mysql_query function mixed in with the mysqli functions.
I got the code to work for me by changing
mysql_query($order);
To:
mysqli_query($con, $order);
You can also debug what was passed to the script by simply printing the $_POST array:
print_r($_POST);
I am newbie to php.I have coded auto-complete text box using php,and i have a submit button.i have not given form action.
This is the HTML form code that i used for autocomplete textbox.this autocomplete textbox selects the value
<form method="post" autocomplete="off">
<p>
<b>Theater Name</b> <label>:</label>
<input type="text" name="theater" id="theater" />
</p>
<input type="submit" value="Submit" />
</form>
I have another php function that retrieves the values based on where clause.in the where statement i want to use selected value from form.
for ex: select address from theaters where theater_name ="form value"
How to use the form value in php function?can any one help me?
<?php
$con = mysql_connect("localhost","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("theaterdb", $con);
$result = mysql_query("SELECT * FROM theter
WHERE theater_name="<!-- This could be value that we get after clicking submit button-->);
while($row = mysql_fetch_array($result))
{
echo $row['thearer_name'];
echo "<br />";
}
?>
Thanks in advance......
You could get the value from $_POST by $_POST['theater'].
And note, you should not use this value directly in the sql, you need to escape it to prevent sql injection.
$theater = mysql_escape_string($_POST['theater']);
$result = mysql_query("SELECT * FROM theter WHERE theater_name='$theater'";
Last, you could take a look at PDO, which is suggested over the old mysql_* functions.
First, change your submit button code to the following:
<input name="submit" type="submit" value="Submit" />
Now, this is the code you should use for the query:
<?php
if (isset($_POST['submit'])) {
$con = mysql_connect("localhost","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("theaterdb", $con);
$result = mysql_query("SELECT * FROM theater
WHERE theater_name='" . mysql_real_escape_string($_POST['theater']) . "'");
while($row = mysql_fetch_array($result))
{
echo $row['theater_name'];
echo "<br />";
}
}
First, I check that the user submitted the form. Then, I escape the data he has submitted and inserting it into your query.
* NOTE: All of what I've wrote is based on the assumption that the code is executed after the form is submitted.
* ANOTHER NOTE: You should read about using PDO rather than MYSQL functions.
First and foremost, try using mysqli instead of mysql (mysqli_query, mysqli_connect). There are numerous security / speed advantages to using it and it has pretty much the exact same functionality.
While the above answers mention using $_POST['theater'] (the name of your input), be SURE to escape your post before putting it into your query.
$con = mysqli_connect("localhost","root", "YOUR PASSWORD HERE", "YOUR DATABASE HERE");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
// No need for this, please see the updated mysqli_connect as the 4th parameter selects your DB
//mysqli_select_db("theaterdb", $con);
// Please notice the last parameter of the mysqli_real_escape_string is your Input's POST
$query = "SELECT * FROM theater WHERE theater_name=".mysqli_real_escape_string($con, $_POST['theater']);
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result))
{
echo $row['thearer_name'];
echo "<br />";
}
$_POST["your_variable_name"] // for POST
$_GET["your_variable_name"] // for GET
For in-depth information please go to: http://www.php.net/manual/en/language.variables.external.php
i’m new to codeigniter and i’m working on a project. i have to create a dynamic drop down menu with values from my database, when a selection is made in the drop down as soon as you click on the submit button a new page has to occur where all the cities associated with the province selected in the drop menu appear, the cities are also in my database .My database consists of an id field, province field and a cities field.The drop menu is fine but cant seem to make the cities appear in the next page. your help will be highly appreciated
ok here's my code
this is from my view file which displays my drop menu this side is ok
<?
function writeCities($id)
{
$con = mysql_connect("localhost","root","");
if (!$con) die('Could not connect: ' . mysql_error());
mysql_select_db("msansi", $con);
$query = "SELECT cities FROM provinces WHERE id =";
$query .= $id;
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo $row[0];
}
function populateDropBox()
{
$con = mysql_connect("localhost","root","");
if (!$con) die('Could not connect: ' . mysql_error());
mysql_select_db("msansi", $con);
$result = mysql_query("SELECT id,title,cities FROM provinces");
while($row = mysql_fetch_array($result))
{
echo "<option value=$row[0]>" . $row['title']."</option>";
}
}
?>
<form name="myform" action="http://localhost/CodeIgniter_1.7.3/index.php/ndivhuho/submit" method="post">
<select name = "province" onChange="onChangeDropBox();"/>
<? populateDropBox(); ?>
<input type="submit" value="submit"; />
</form>
and here's my other view file which is supposed to display the cities in a text area
<?
function writeCities($id)
{
$con = mysql_connect("localhost","root","");
if (!$con) die('Could not connect: ' . mysql_error());
mysql_select_db("msansi", $con);
$query = "SELECT cities FROM provinces WHERE id =";
$query .= $id;
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo $row[0];
}
?>
<script type="text/javascript">
function onChangeDropBox()
{
var selected =0;
selected = document.myform.province.value;
var t = "<? writeCities(1);?>";
document.myform.textArea.value = t;
}
</script>
<form name=myform>
<textarea name="citites" readonly="true";></textarea>
</form>
i'm sure theres something i need to do in my controller which i don't know of
thanxx in advance!!!
Take a look at the following two guides on how to do what you're talking about doing:
http://php-ajax-code.blogspot.com/2007/07/ajax-triple-dropdown-with-states-cities.html
http://roshanbh.com.np/2007/12/change-dropdown-list-options-values-from-database-with-ajax-and-php.html
There are a few problems here.
The code you have provided is using native php functions to connect to mysql. You should be using the proper CodeIgniter libraries. Start by reading this.
http://codeigniter.com/user_guide/database/examples.html
Once you've read that..
"this is from my view file which displays my drop menu"
Take the code out of your view file! The database calls should be in a model, and that should be called by a controller, which passes the data through to your view file.
Probably read this too:
http://en.wikipedia.org/wiki/Model%E2%80%93View%E2%80%93Controller