PHP Search and Query Results - php

Here is my issue. I have a database I want to search by name only. If there are similar names I want it to pop up and give an option to pick which one. Once you do and click search it goes into a search.php file... I want to display results but the GET method does not seem to work.
Here is my form.
<form action="search.php" method="GET">
<input type="text" name="query" />
<input type="submit" value="Search" />
Here is my PHP search
<?php
mysql_connect("localhost", "dbname", "password") or die("Error connecting to database: ".mysql_error());
/*
localhost - it's location of the mysql server, usually localhost
root - your username
third is your password
if connection fails it will stop loading the page and display an error
*/
mysql_select_db("ambassador") or die(mysql_error());
/* tutorial_search is the name of database we've created */
$query = $_GET['query'];
// gets value sent over search form
$min_length = 3;
// you can set minimum length of the query if you want
if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT * FROM member
WHERE (`Name` LIKE '%".$query."%')") or die(mysql_error());
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysql_fetch_array($raw_results)){
}
}
else{ // if there is no matching rows do following
echo "No results";
}
}
else{ // if query length is less than minimum
echo "Minimum length is ".$min_length;
}
?>
Then I try to use this method to get results from database.
<?php echo $_GET['Name']; ?>
Thanks for all your help!

This is not an answer , i put code here because it's not well formated in the comment.
So , try this part of code ,it should display result according to the name in the form :
HTML:
<form action="search.php" method="GET">
<input type="text" name="name" />
<input type="submit" value="Search" />
</form>
PHP:
<?php
mysql_connect("localhost", "dbname", "password") or die("Error connecting to database: ".mysql_error());
mysql_select_db("ambassador") or die(mysql_error());
//check if variable $_POST['name'] has a value
if(isset($_GET['name'])) $name=$_GET['name'];
else $name="";
$raw_results = mysql_query("SELECT * FROM member where name='".$name."'") or die(mysql_error());
while($results = mysql_fetch_array($raw_results,MYSQL_ASSOC)){
echo $results['name'].'<br/>';
}
?>

Related

Insert echo into textfield using Get Method

This is a continuation from my previous question "Display ID Number in URL & fetch database results from ID Number into textfields", but dubbed as another one.
Thanks for helping me out #Robbie. If only I can upvote more :')
Now for the topic. I can't seem to get to insert the value displayed as an href link into the textfield supposedly I know I'm doing this wrong obviously since I can't get it to work I would like some further assistance.
Here are the codes used: index.html
<html>
<head>
<title>Search Engine</title>
</head>
<body>
<form method='get' action="results.php">
<label> What do you like to search for?</label>
<input type='text' name='search'>
<button type='submit'>Search</button>
</form>
</body>
</html>
And this is for the actual php process:
<?php
mysql_connect("localhost","root","") or die (mysql_error());
mysql_select_db("ntmadb") or die (mysql_error());
$var = "hello";
$clean = mysql_real_escape_string($_GET['search']);
$hello = mysql_query("SELECT * FROM members WHERE id = '$clean'") or die (mysql_error());
if(mysql_num_rows($hello) >=1) {
//getdata
while($i = mysql_fetch_array($hello)){
echo ''.$i['firstname'].'';
}
}
else{
echo "No results found, sorry:(";
}
?>
<html>
<input type='text' name="firstname" value="<?php echo $firstname;?>" ></input></br>
<input type='text' name="lastname" value="<?php echo $lastname;?>" ></input></br>
</html>
Thanks alot again
Azuren, you actually gone backwards from your first question (Display ID Number in URL & fetch database results from ID Number into textfields) as you've reverted to mysql_ functions and not mysqli_ The former (mysql_) have been removed from PHP.
I've rewritten using mysqli (roughly - you may need to debug) and answered the question at the same time.
If a tutorial includes any function that begins mysql_ then find another one!
You need to define $firstname and $lastname; I'd suggest doing so as follows:
<?php
mysql_connect("localhost","root","") or die (mysql_error());
mysql_select_db("ntmadb") or die (mysql_error());
$firstname = '';
$lastname = '';
if (isset($_GET['search'])) {
if ($stmt = $mysqli->prepare("SELECT firstname, lastname FROM members WHERE id = ?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $_GET['search']);
/* bind result variables */
$stmt->bind_result($firstname, $lastname );
/* execute query */
$stmt->execute();
/* fetch values */
while ($stmt->fetch()) {
echo ''.htmlspecialchars($firstname).'';
}
}
}
}
?>

php keyworks search do not works

i want to retrieve data in database by using search engine i create.
it pass the search keywords from testseach.php to searchTitle.php.
here is my code for test seach.php
>!DOCTYPE html>
<html>
<head><title></title>
</head>
<body>
<form action="searchTitle.php" method="GET" class="formright">
<input type="text" name="keywords" placeholder="Search">
<input type="submit" value="search">
</form>
</body>
</html>
here is my searchtitle.php which pass the keywords from testsearch.
<? php
require_once 'database_conn.php'
//collect search title
if(isset($_GET['keywords'])){
$searchq = $_GET['keywords'];
$searchq = preg_replace("#[^a-z]#i" , "", $searchq);
$query = mysql_query("SELECT eventTitle FROM te_events where eventTitle LIKE '%searchq%'") or die("could not search!");
$count = mysqli_num_rows($query);
if($count==0){
echo "<p>There was no search result!</p>\n";
}
else{
while ($row = mysql_fetch_assoc($query)){
$title = $row['eventTitle'];
$id = $row['eventID'];
echo "<p>$title</p>\n";
}
}
}
?>
however, it shows this error
There was no search result! \n"; } else{ while ($row =
mysql_fetch_assoc($query)){ $title = $row['eventTitle']; $id =
$row['eventID']; echo " $title
\n"; } } } ?>
i pretty sure that my database connection is working and i don't see any typo in my code.
can anyone tell me what's is my problem?
There are some mistake
1)$query = mysql_query("SELECT * FROM countries",$connection) or die("could not search!");
In mysql_query you add connection variable
please refer syntax as per php documentation
2) You use $count = mysqli_num_rows($query); for get number of raw but you use mysql_num_rows instead of mysqli_num_rows
OR
Please check php version and that compatible with mysql or mysqli
please check it also because that may cause that type of issue also
this answer may be help you.

Opencart Custom mysql search form

I am creating a simple custom search form. This form searches the table 'oc_product' where i created a new column 'gcode'. I have inserted a sample data in this column for one of the products. Is it necessary to make a new db/mysql connect in php within a new tpl file i created just like 'information/contact'. I call this 'gcode/gcode'.
I tried but unable to get result form the search. It redirected to index.php.
My code is:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="searchform">
<input type="text" name="name">
<input type="submit" name="submit" value="Search">
</form>
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("/^[ a-zA-Z]+/", $_POST['name'])){
$name=$_POST['name'];
//connect to the database
$db=mysql_connect ("localhost", "username_demo", "pwddemo123") or die ('I cannot connect to the database because: ' . mysql_error());
//-select the database to use
$mydb=mysql_select_db("db_demo");
//-query the database table
$sql="SELECT * FROM oc_product WHERE gcode LIKE '%" . $name . "%'";
//-run the query against the mysql query function
$result=mysql_query($sql);
//-create while loop and loop through result set
while($row=mysql_fetch_array($result)){
$gcode =$row['gcode'];
//-display the result of the array
echo '<span>'."This product is genuine".$gcode.'</span>';
}
}
else{
echo "<p>Please enter a search query</p>";
}
}
}
Any example to search a column and fetch data from a column.
Don't quite understand your question. Do you want to fetch data from ONE column? Also use mysql_fetch_assoc instead mysql_fetch_array
And replace $_GET with $_POST
Also your select statement is wrong, so do this:
<?
$sql="SELECT * FROM oc_product WHERE gcode LIKE '%$name%'";
$result = mysql_query($sql);
$results = mysql_num_rows($result);
for($i=0; $i<$results; $i++)
{
$row = mysql_fetch_assoc($result);
$gcode = $row['gcode'];
// Here list it the way you want
echo $gcode.'<br>';
}
?>
you would need to create a model or simply add this field in the search model to be searched by it. i am not sure if that is what you want to accomplish, also you would want to make sure to sanitize the request and escape it before you get one of the SQL injection attacks.

Changing product picture

<?php
$Name=$_POST['txtName'];
$Desc=$_POST['txtDesc'];
$path1 = $_FILES["txtFile"]["name"];
move_uploaded_file($_FILES["txtFile"]["tmp_name"],"../Products/" .$_FILES["txtFile"]["name"]);
//** Establish Connection with MYSQL
$con = mysql_connect("localhost","root");
// Select Database
mysql_select_db("jmmc", $con);
// Specify the query to Update Record
$sql = "Update admin_category set CategoryName='".$Name."',Description='".$Desc."',Image='".$path1."' where CategoryId=".$Id."";
// Execute query
mysql_query($sql,$con);
// Close The Connection
mysql_close($con);
?>
Send me error you are getting from code.
Check your file location path that is not true
or
may be you did not create folder Product and check your database make confirm you have right column names
Check Your all Variables like $Id,$Name,$Desc have a proper values
like
(where CategoryId=".$Id."")
you need to define enctype,method type(get or post) in form and make html like this:
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="txtFile" >
<input type="hidden" name="txtDesc" value="aaaaa">
<input type="hidden" name="txtName" value="naveed">
<input type="submit" name="submit_button">
</form>
You need to define PHP code in isset statement like this:
<?php
if (isset($_POST['submit_button'])) {
$fileName = $_FILES["txtFile"] ["name"];
if (isset($fileName)) {
$Name=$_POST['txtName'];
$Desc=$_POST['txtDesc'];
$path1 = $_FILES["txtFile"]["name"];
move_uploaded_file($_FILES["txtFile"]["tmp_name"],"../Products/" .$_FILES["txtFile"]["name"]);
//** Establish Connection with MYSQL
$con = mysql_connect("localhost","root");
// Select Database
mysql_select_db("stackoverflow", $con);
// Specify the query to Update Record
$sql = "Update admin_category set CategoryName='".$Name."',Description='".$Desc."',Image='".$path1."' where CategoryId=".$Id."";
// Execute query
mysql_query($sql,$con);
// Close The Connection
mysql_close($con);
}
}
?>

PHP and MySQL form, what am I doing wrong?

I have a table that has the user ID already in it, but some of the information is missing and that is where I need the user to input it themselves. With the URL of the form I have their ID in it... winnerpage.php?ID=123
I am having troubles getting the code to work. Any help would be great!
This is the code on that winnerpage.php
<form enctype="multipart/form-data" action="winnerpage.php" method="POST">
ID: <input name="ID" type="text" value="<?=$ID?>" /><br/>
First Name: <input type="text" name="FN"><br />
Last Name: <input type="text" name="LN"><br />
Email: <input type="text" name="EM"><br />
Phone: <input type="text" name="PH"><br />
<input type="submit" name="edit" value="edit"></form> <br>
<?
require_once('mysql_serv_inc.php');
$conn = mysql_connect("$mysql_server","$mysql_user","$mysql_pass");
if (!$conn) die ("ERROR");
mysql_select_db($mysql_database,$conn) or die ("ERROR");
if(isset($_POST['edit']))
{
$sID = addslashes($_POST['ID']);
$sFN = addslashes($_POST['FN']);
$sLN = addslashes($_POST['LN']);
$sEM = addslashes($_POST['EM']);
$sPH = addslashes($_POST['PH']);
mysql_query('UPDATE winner SET FN=$sFN, LN=$sLN, EM=$sEM, PH=$sPH
WHERE ID=$sID') or die (mysql_error());
echo 'Updated!';
}
$query = "select * from winner order by ID";
$result = mysql_query($query);
?>
<?
while ($link=mysql_fetch_array($result))
{
echo 'Unique ID - Completion Time - First Name - Last Name - Email - Phone<br/>'.$link[ID].' -' .$link[FN].' - '.$link[LN].' - '.$link[EM].' - '.$link[PH].'<br>';
}
?>
1)
ID: <input name="ID" type="text" value="<?=$ID?>" /><br/>
Where do you get that $ID? Are you doing something like $_GET['ID'] or are you relying on safe_mode being ON? (it's not clear from the code you provided)
(better yet, if(isset($_GET['ID'])) { $ID = (int)$_GET['ID'] }
2) Please don't to that. Don't use addslashes(). Use mysql_real_escape_string() or, even better, prepared statements. Addslashes is not utterly reliable in escaping datas for queries.
sID = (int)$_POST['ID'];
$sFN = mysql_real_escape_string($_POST['FN']);
$sLN = mysql_real_escape_string($_POST['LN']);
$sEM = mysql_real_escape_string($_POST['EM']);
$sPH = mysql_real_escape_string($_POST['PH']);
Also, add 'value=""' to each input field (not mandatory)
3) encapsulate values in query:
mysql_query("UPDATE winner SET FN='".$sFN."', LN='".$sLN."', EM='".$sEM."', PH='".$sPH."' WHERE ID='".$sID."'") or die (mysql_error());
Maybe try:
mysql_query("UPDATE winner SET FN='$sFN', LN='$sLN', EM='$sEM', PH='$sPH' WHERE ID=$sID") or die (mysql_error());
mysql_query('UPDATE winner SET FN=$sFN, LN=$sLN, EM=$sEM, PH=$sPH WHERE ID=$sID')
the query is encapsulated by single-quotes, so the variables inside will not be parsed.
At first glance I would say that you need:
1) Quote marks around some of the values you are inserting into the table (any strings for example)
2) Quote marks around the names of the fields when you try to echo them out at the end ($link['ID'] for example)

Categories