This question already has answers here:
How can I get a PHP value from an HTML form?
(2 answers)
Closed 1 year ago.
I am currently trying to complete a project where the specifications are to use a search form to search through a packaging database. The database has lots of variables ranging from Sizes, names, types and meats. I need to create a search form where users can search using a number of different searches (such as searching for a lid tray that is 50 cm long).
I have spent all day trying to create some PHP code that can search for info within a test database I created. I have had numerous amounts of errors ranging from mysql_fetch_array errors, boolean errors and now currently my latest error is that my table doesn't seem to exist. Although i can enter data into it (html and php pages where I can enter data), I don't know what is causing this and I have started again a few times now.
Can anyone give me some idea or tips of what I am going to have to do currently? Here is just my small tests at the moment before I move onto the actual sites SQL database.
Creation of database:
<body>
<?php
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if (mysql_query("CREATE DATABASE db_test", $con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
mysql_select_db("db_test", $con);
$sql = "CREATE TABLE Liam
(
Code varchar (30),
Description varchar (30),
Category varchar (30),
CutSize varchar (30),
)";
mysql_query($sql, $con);
mysql_close($con);
?>
</body>
HTML search form page:
<body>
<form action="form.php" method="post">
Search: <input type="text" name="term" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
The PHP code I am using to attempt to gather info from the database
(I have rewritten this a few times, this code also displays the "table.liam doesn't exist")
<body>
<?php
$con = mysql_connect ("localhost", "root", "");
mysql_select_db ("db_test", $con);
if (!$con)
{
die ("Could not connect: " . mysql_error());
}
$sql = mysql_query("SELECT * FROM Liam WHERE Description LIKE '%term%'") or die
(mysql_error());
while ($row = mysql_fetch_array($sql)){
echo 'Primary key: ' .$row['PRIMARYKEY'];
echo '<br /> Code: ' .$row['Code'];
echo '<br /> Description: '.$row['Description'];
echo '<br /> Category: '.$row['Category'];
echo '<br /> Cut Size: '.$row['CutSize'];
}
mysql_close($con)
?>
</body>
try this out let me know what happens.
Form:
<form action="form.php" method="post">
Search: <input type="text" name="term" /><br />
<input type="submit" value="Submit" />
</form>
Form.php:
$term = mysql_real_escape_string($_REQUEST['term']);
$sql = "SELECT * FROM liam WHERE Description LIKE '%".$term."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)){
echo 'Primary key: ' .$row['PRIMARYKEY'];
echo '<br /> Code: ' .$row['Code'];
echo '<br /> Description: '.$row['Description'];
echo '<br /> Category: '.$row['Category'];
echo '<br /> Cut Size: '.$row['CutSize'];
}
Edit: Cleaned it up a little more.
Final Cut (my test file):
<?php
$db_hostname = 'localhost';
$db_username = 'demo';
$db_password = 'demo';
$db_database = 'demo';
// Database Connection String
$con = mysql_connect($db_hostname,$db_username,$db_password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db_database, $con);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="" method="post">
Search: <input type="text" name="term" /><br />
<input type="submit" value="Submit" />
</form>
<?php
if (!empty($_REQUEST['term'])) {
$term = mysql_real_escape_string($_REQUEST['term']);
$sql = "SELECT * FROM liam WHERE Description LIKE '%".$term."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)){
echo 'Primary key: ' .$row['PRIMARYKEY'];
echo '<br /> Code: ' .$row['Code'];
echo '<br /> Description: '.$row['Description'];
echo '<br /> Category: '.$row['Category'];
echo '<br /> Cut Size: '.$row['CutSize'];
}
}
?>
</body>
</html>
You're getting errors 'table liam does not exist' because the table's name is Liam which is not the same as liam. MySQL table names are case sensitive.
Related
This question already has answers here:
search data from html input in mysql
(2 answers)
Closed 1 year ago.
I am trying to search the username from table by using form method in HTML with submit button, and what i really want is that when user write his email address in input box and press submit, the query should echo username associated with that email address.
But the problem is that when I press search button, it is showing all the usernames on that table instead of only one. My table "payments" containing the following values: id, product id, payer_email, username, password.
My code is as under. Thanks in advance.
<?php
// Database Connection String
$con = mysql_connect($db_hostname,$db_username,$db_password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db_database, $con);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="" method="post">
Search: <input type="text" name="term" /><br />
<input type="submit" value="Submit" />
</form>
<?php
if (!empty($_REQUEST['term'])) {
$term = mysql_real_escape_string($_REQUEST['term']);
$sql = "SELECT * FROM payments WHERE payer_email LIKE '%".$term."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)){
echo 'Username: ' .$row['username'];
}
}
?>
</body>
</html>
try this
<?php
if (!empty($_REQUEST['payer_email'])) {
$term = mysql_real_escape_string($_REQUEST['payer_email']);
$sql = "SELECT * FROM payments WHERE payer_email ='{$term}'";
$r_query = mysql_query($sql);
$row = mysql_fetch_assoc($r_query)
echo 'Username: ' .$row['username'];
}
?>
I am creating a simple page which updates a single record tempKey=1, single field reqdTemp MySQL dBase. I have the form working fine; it updates the record, then returns to the initial form ready for the user to change the temperature again.
Q: I would like the form to be pre-populated with the existing information from the database so the user sees the current required temperature about to be changed. I'm not sure where to start!!
The form, updateTemperature.php, is this:
<html>
<body>
<h1>RPi BBQ - Set Temperature</h1>
<form action="insert.php" method="post">
<p>Set Temperature: <input type="text" name="setTemp" /></p><br><br>
<input type="submit" value="Set Temperature" />
</form>
</body>
</html>
The post script, insert.php is this:
<?php
require_once 'login.php';
$con=mysqli_connect($hh,$un,$pw,$db);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo 'Connected successfully';
$sql = "UPDATE PiBQ_Temp SET reqdTemp = '$_POST[setTemp]' WHERE tempKey = 1";
mysqli_query($con,$sql);
echo "1 record added";
header ('location: PiBQ_Temp2.php');
mysql_close($con)
?>
To pre-populate the form, query the database for the current value and set that in the returned HTML. So your updateTemperature.php could become something like this:
<?php
require_once 'login.php';
$con=mysqli_connect($hh,$un,$pw,$db);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo 'Connected successfully';
$currentTemp = 100; // some default
$sql = "SELECT reqdTemp FROM PiBQ_Temp WHERE tempKey = 1";
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$currentTemp = $row['reqdTemp'];
}
mysql_close($con);
?>
<html>
<body>
<h1>RPi BBQ - Set Temperature</h1>
<form action="insert.php" method="post">
<p>Set Temperature: <input type="text" name="setTemp" value="<?= $currentTemp ?>" /></p><br><br>
<input type="submit" value="Set Temperature" />
</form>
</body>
</html>
I have creacted an SQL Database. I succsess fully insert data into database, but i want to search from database.
HTML
<body>
INSERT AREA
<br>
<form action="demo.php" method="post"/>
<p>imei: <input type="text" name="input1"/> </p>
<select name="input2">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<br>
<br>
<input type="submit" src="submit.png" alt="Submit Form" />
</form>
Search AREA
<br>
<form action="form.php" method="post">
Search: <input type="text" name="term" /><br />
<input type="submit" value="Submit" />
</form>
</body>
demo.php
<?php
define('DB_NAME', '#');
define('DB_USER', '#');
define('DB_PASSWORD', 'mypass');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
}
$value = $_POST['input1'];
$value2 = $_POST['input2'];
$sql = "INSERT INTO demo (input1, input2) VALUES ('$value', '$value2')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
mysql_close();
?>
So all these work perfect , i insert data to SQL Database fine, but check the next php code for search, isn't return any info it just open with-out return value. *i have wipe the database info.
Database name : demo
Host name :localhost
form.php
<?php
$db_hostname = 'localhost';
$db_username = 'my username';
$db_password = 'my pass';
$db_database = 'demo';
// Database Connection String
$con = mysql_connect($db_hostname,$db_username,$db_password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db_database, $con);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="demo.php" method="post"/>
<p>imei: <input type="text" name="input1"/> </p>
<select name="input2">
<option value="1">111111111111111111111</option>
<option value="2">222222222222222222</option>
<option value="3">33333333333333333</option>
<option value="4">4444444444444444</option>
</select>
<br>
<br>
<input type="image" src="submit.png" alt="Submit Form" />
</form>
<br>
<form action="form.php" method="post">
<input type="text" name="term" /><br />
<input type="submit" value="Submit" />
</form>
<?php
if (!empty($_REQUEST['term'])) {
$term = mysql_real_escape_string($_REQUEST['term']);
$sql = "SELECT * FROM demeo WHERE Description LIKE '%".$term."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)){
echo 'Primary key: ' .$row['PRIMARYKEY'];
echo '<br /> Code: ' .$row['input1'];
echo '<br /> Description: '.$row['input2'];
}
}
?>
</body>
</html>
By looking at your first example, it seems that in the second one, your table and column names are incorrect.
Replace your current query:
SELECT * FROM demeo WHERE Description LIKE '%".$term."%'
With this query:
SELECT * FROM demo WHERE input2 LIKE '%".$term."%'}
Also consider the suggestions of the other users to avoid sql injections.
I am trying to get a video play to play from a database. I have a form with the following code:
<form action="abs3xvideos.php" method="POST" enctype="multipart/form-data">
<input type="file" name="id" />
<input type="submit" name="submit" value="UPLOAD!" />
<form action="abs3xvideos.php">
Search ABS3X:
<input type="search" name="googlesearch">
<input type="submit">
</form>
I then have another page the form is linked to with the following code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
define('DB_Name', 'gaufensr_abs3x');
define('DB_User', 'gaufensr_owner');
define('DB_Password', 'password');
define('DB_Host', 'localhost');
$link = mysql_connect(DB_Host, DB_User, DB_Password);
if (!$link) {
die('could not connect:' . mysql_error());
}
$db_selected = mysql_select_db(DB_Name, $link);
if (!#db_selected) {
die('can\t use' . DB_Name. ': ' . mysql_error());
}
echo 'CONNECTED SUCCESSFULLY';
$id = $_POST['id'];
$value = $_POST['id'];
$sql = "INSERT INTO videos (video_name) VALUES ('$value')";
if (!mysql_query($sql)) {
die(`ERROR: ` .mysql_error());
}
if (isset($_POST['id'])){
$id = $_POST['id'];
$query = mysql_query("SELECT * FROM `videos` WHERE id='$id'");
while($row = mysql_fetch_assoc($query))
{
$id = $row['id'];
$video_name = $row['video_name'];
}
echo "You are watching " .$id. "<br />";
echo "<embed src=`$id` width='560' height='315'></embed>";
}
else
{
echo "Error!";
}
mysql_close();
?>
I get the following error message when I try to upload a video using the form page that I created:
CONNECTED SUCCESSFULLY
Notice: Undefined index: id in /home1/gaufensr/public_html/abs3xvideos.php on line 39
Notice: Undefined index: id in /home1/gaufensr/public_html/abs3xvideos.php on line 40
Error!
I am at a loss. I spoke with someone on stackflow earlier and they suggested that something might be wrong with my while loop but I am not to sure what the mistake could be. Should I separate the PHP code into different pages maybe?
Did you urlencode the name?
$video_name = urlencode($row['video_name']);
Or rawurldecode may work better.
$video_name = rawurldecode($row['video_name']);
you forget to close form
Use
<form action="abs3xvideos.php" method="post" enctype="multipart/form-data">
<input type="file" name="id" />
<input type="submit" name="submit" value="UPLOAD!" />
</form>//from close here
<form action="abs3xvideos.php">
Search ABS3X:
<input type="search" name="googlesearch">
<input type="submit">
</form>
I have written this code to create a search form and get results from mysql table:
<?
$db_hostname = 'localhost';
$db_username = 'root';
$db_password = '';
$db_database = 'jatc_university_j32';
// Database Connection String
$con = mysql_connect($db_hostname, $db_username, $db_password);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db_database, $con);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="" method="post">
Search: <input type="text" name="FieldValue" /><br />
<input type="submit" value="Submit" />
</form>
<?
if (!empty($_REQUEST['FieldValue'])) {
$FieldValue = mysql_real_escape_string($_REQUEST['FieldValue']);
$result = mysqli_query($con, "SELECT Fieldvalue from #__rsform_submission_values WHERE FieldName = 'candidatname'");
while ($row = mysqli_fetch_array($result)) {
echo $row;
echo "<br>";
}
}
?>
</body>
</html>
In my database table I have FieldName: candidatname, candidatsurname and FieldValue: John, Wayne etc.
I want to search entering a name and return the other details for this candidate
Anyway when I run code nothing happens
Can you please check if I am doing wrong something because I get the same result in a lot of trials
1.Nothing happens beacuse you are using <? ?> for php, but you should use <?php ?>
2.Your form method is post then you should check variblae like this on form submit:
if (!isset($_POST['FieldValue']))
3. "SELECT Fieldvalue from #__rsform_submission_values WHERE FieldName = 'candidatname'"
instead of candidatename, give the value that you got from the form:
"SELECT Fieldvalue from #__rsform_submission_values WHERE FieldName = '".$FieldValue."'" <BR>
4. <input type="submit" value="Submit" /> add a name property to this like:
<input type="submit" value="Submit" name="Submit"/>
and it will work, i tested after applying these changes!
Try this:
<?php
$formpartone = <<<EODformpartone
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="{$_SERVER['PHP_SELF']}" method="get">
Search: <input type="text" name="FieldValue" value=""/><br />
<input type="submit" value="Submit" />
</form>
EODformpartone;
$formparttwo = <<<EODformparttwo
</body>
</html>
EODformparttwo;
if (!isset($_GET["FieldValue"]))
{
echo $formpartone;
echo $formparttwo;
}
ELSE {
function search_candidate(){
$host = "localhost";
$user = "root";
$password = "";
$database = "jatc_university_j32";
$searchstring = $_GET["FieldValue"];
$link = mysqli_connect($host, $user, $password, $database);
IF(!$link){
echo ('unable to connect to database');
}
ELSE {
$query = "SELECT candidatename, candidatesurname
FROM (
SELECT c.SubmissionID,
max(CASE WHEN c.FieldName='candidatename' THEN c.Fieldvalue ELSE 0 END) AS 'candidatename',
max(CASE WHEN c.FieldName='candidatesurname' THEN c.Fieldvalue ELSE 0 END) AS 'candidatesurname'
FROM mf2sn_rsform_submission_values as c
GROUP BY c.SubmissionID
) a
WHERE a.candidatename LIKE '".$searchstring."' OR a.candidatesurname LIKE '".$searchstring."'";
$result = mysqli_query($link, $query);
echo "<table>";
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo "<tr><td>".$row['candidatename']."</td><td>".$row['candidatesurname']."</td></tr>";
} echo "</table>";
}
mysqli_close($link);
}
echo $formpartone;
echo search_candidate();
echo $formparttwo;
}
?>
Sample table mysql
CREATE TABLE candidates
(
id int auto_increment primary key,
SubmissionID int,
FieldName varchar(20),
Fieldvalue varchar(30)
);
INSERT INTO candidates
(SubmissionID, FieldName, Fieldvalue)
VALUES
(1,'candidatename','Bob'),
(1,'candidatesurname', 'Smith'),
(2,'candidatename','Jack'),
(2,'candidatesurname', 'Doe');
SQLFiddle demo of the sample data
You should look into the validation and sanitation of the search string to avoid SQL injection. And what to do when no candidates are found with the name you inserted. However, I think for now it is important to test if everything works.