I have several articles in my db and search on my site. if the user does not enter anything and click search, then displays all articles. How to catch empty request?
Code:
<?php
mysql_connect("localhost", "user", "password") or die("Error");
mysql_select_db("selv_hram") or die("Error");
mysql_query('SET names "utf8"');
if (isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = htmlspecialchars($searchq);
$query = mysql_query("SELECT * FROM articles WHERE title LIKE '%$searchq%' OR text_article LIKE '%$searchq%'");
$count = mysql_num_rows($query);
$output = '';
if ($count == 0) {
$output = 'Nothing find';
}else {
while ($row = mysql_fetch_array($query)) {
$title = $row['title'];
$text = $row['text_article'];
$id = $row['id'];
$output .= '<div>'.$title.' '.$text.'</div>';
}
}
}
?>
<div class="content-article">
<form name="search" action="index.php" method="post" class="search-form">
<input type="text" name="search" placeholder="search" />
<input type="submit" value=">>">
<?php print("$output"); ?>
</div>
After you read this post about SQL-injection,
change
if (isset($_POST['search'])) {
to
if (!empty($_POST['search'])) {
This is simple validation.
if(empty($_POST['search'])) {
echo "Empty search query";
} else {
//search query
}
Check the user input first, if it is empty change the query. like below
$searchq = htmlspecialchars($searchq);
if(trim($searchq) == ''){
$query = mysql_query("SELECT * FROM articles");
}else{
$query = mysql_query("SELECT * FROM articles WHERE title LIKE '%$searchq%' OR text_article LIKE '%$searchq%'");
}
Dont use depreciated mysql_ functions. Go for mysqli
Related
I've got my code which is searching my database and table for a certain condition but when I search it doesn't return any result. I've looked at a few tutorials and cant find the issue. Any help is appreciated. I know the code is outdated and I should be using mysqli. I will be changing this when the issue is rectified.
<?php
$output = NULL;
if(isset($_POST['submit'])){
mysql_connect("localhost", "root", "") or die (mysql_error());
mysql_select_db("first_db") or die("can not connect");
$search = $mysql->real_escape_string($_POST['search']);
$resultSet = $mysql->query("SELECT * FROM voulunteer WHERE Name LIKE '%search%'");
if($resultSet->num_rows > 0){
while($rows = $resultSet->fetch_assoc())
{
$StaffStatus = $rows['StaffStatus'];
$name = $rows['Name'];
$output = "Staff Status: $StaffStatus<br/>name: $Name<br/><br/>";
}
}else{
$output = "No results";
}
}
?>
<form method-"POST">
<input type="TEXT" name"search" />
<input type="SUBMIT" name="submit" value="Search" />
</form>
Your query is written wrong
instead of
$resultSet = $mysql->query("SELECT * FROM voulunteer WHERE Name = LIKE '%search&'");
try this
$resultSet = $mysql->query("SELECT * FROM voulunteer WHERE Name LIKE '%search%'");
edit: added nogad's comment about changing the & to %
Try the query in phpmyadmin first. If there's an error in the query it will tell you
I have HTML code with checkbox and submit button as below
<form action="checkboxes.php" method="post">
<input type="checkbox" name="checkbox1" value="Yes">4K</input>
<input type="submit" name="formSubmit" value="Submit" ></input>
</form>
And in my PHP I have a file "config.php" that his function is to connect to my database:
<?php
/* Database connection */
$sDbHost = 'localhost';
$sDbName = 'testowanie';
$sDbUser = 'root';
$sDbPwd = '';
$dbcon = mysqli_connect ($sDbHost, $sDbUser, $sDbPwd, $sDbName);
?>
And a second PHP file:
<?php
include('config.php');
$sqlget = "SELECT * FROM monitory";
$sqldata = mysqli_query($dbcon, $sqlget)or die("Can't connect to the database");
if(isset($_POST['checkbox1']) &&
$_POST['checkbox1'] == 'Yes')
{
while($row = mysqli_fetch_array($sqldata, MYSQLI_ASSOC)) {
echo '.';
echo $row['cena'];
}
}
?>
This all three connected files each others do that if the checkbox is checked this SQL statement are executed: SELECT cena FROM monitory; but I want to execute this statement "SELECT * FROM monitory WHERE cena=1000;
I tried to do this like around 2 hours but I really don't know how to do this.
So You want to choose one of two different queries according to input conditions. Then do it so :-)
<?php
include('config.php');
if (isset($_POST['checkbox1']))
$sqlget = "SELECT * FROM monitory WHERE cena = 1000";
else
$sqlget = "SELECT * FROM monitory";
$sqldata = mysqli_query($dbcon, $sqlget)or die("Can't connect to the database");
while($row = mysqli_fetch_array($sqldata, MYSQLI_ASSOC)) {
echo '.';
echo $row['cena'];
}
I have a little problem in php.
problem is that i want to search MySQL table by php coding.
In php i want to use Drop down menu And a text field.
I have two MySQL table name is category and products, now i use category entries
in drop-down menu (by cat_name).and in the search text area
i want write any product name selecting by cat_name from drop down menu and then click on search button. Then it will show me the result from product table in table format.
Can any one help me
Thanks.
i have tow category: Mobile and Laptop in categories table and
i have many products name: Dell, Hp, Toshiba, Samsung, Iphone etc...in products table
1. categories
cat_id
cat_name
2. products
product_id
product_cat
product_name
product_price
I have php code. this working correct till populate cat_name from database in drop-down.
result.php
<?php
mysql_connect ("localhost", "root","") or die (mysql_error());
mysql_select_db ("ecomerce");
$sql = mysql_query('SELECT cat_name FROM categories ORDER BY cat_name');
$models = array();
while ($row = mysql_fetch_array($sql)){
$models[] = $row;
}
?>
<form action="search.php" method="post">
<select name="term">
<?php
foreach ($models as $model) {
?>
<option value="<?php echo $model['cat_name']?>"><?php echo $model['cat_name']?></option>
<?php
}
?>
</select>
<form >
<input type="text" class="form-control" placeholder="Search a Product">
<input type="submit" name="submit" value="Search" />
</form>
search.php
<?php
mysql_connect ("localhost", "root","") or die (mysql_error());
mysql_select_db ("ecomerce");
if(isset($_POST['term']) {
$term = $_POST['term'];
$query = "SELECT * FROM products WHERE product_cat = '".mysql_escape_string($term)."'";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result) {
// display results
echo 'Product ID '.$row['product_id'];
echo 'product_title: '.$row['product_name'];
echo 'product_price: '.$row['product_price'];
}
}
?>
config.php
<?php
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_USER', 'DB_Username');
DEFINE ('DB_PASSWORD', 'DB_Password');
DEFINE ('DB_NAME', 'Database_Table_Name');
DEFINE ('DBCONN', 'Path/to/dbconnect.php');
?>
dbconnect.php
<?php
$dbconn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
IF (!$dbconn) {
die('Could not connect: ' . mysql_error());
}
IF (!mysql_select_db (DB_NAME)) { die('Could not select table: ' . mysql_error()); }
?>
functions.php
<?php
// Categories
Function Categories($mysql = true) {
$result = array();
IF ($mysql == true) { require(DBCONN); }ELSE{ global $dbconn; } // db connection
// query cats to array
$sql = mysql_query("SELECT cat_name FROM categories ORDER BY cat_name");
while ($row = mysql_fetch_array($sql)){
$result[] = stripslashes($row['cat_name']);
}
mysql_free_result($sql);
IF ($mysql == true) { mysql_close($dbconn); } // close connection
return $result;
}
// Category dropdown
Function ddform_Categories($cats, $post = NULL) {
$result = "";
// set default
IF ((empty($post)) || ($post == "xx")) {
$result .="<option selected value=\"xx\">Choose Category</option>";
}ELSE{
$result .="<option value=\"xx\">Choose Category</option>";
}
foreach ($cats as $category) {
IF ($post == $category) {
$result .="<option selected value=\"".$category."\">".$category."</option>";
}ELSE{
$result .="<option value=\"".$category."\">".$category."</option>";
}
}
return $result;
}
// MySQL Search
Function CategorySearch($mysql = true, $cats, $post) {
$result = "";
$rows = "";
IF ($mysql == true) { require(DBCONN); }ELSE{ global $dbconn; } // db connection
$term = mysql_escape_string($post);
$query = "SELECT * FROM products WHERE product_cat = '$term'";
$sql = mysql_query($query);
IF (mysql_num_rows($sql)) {
while($r = mysql_fetch_array($sql) {
$rows .= "<tr><td>".$r['product_name']."</td><td>$".number_format($r['product_price'])."</td></tr>";
}
mysql_free_result($sql);
}ELSE{
$result = "<p>No Results</p>";
#$result .= "<p>SQL:\n".$query ."</p>"; // debug
}
IF ($mysql == true) { mysql_close($dbconn); } // close connection
IF (!empty($rows)) {
$result = "<table>".$rows."</table>";
}
return $result;
}
?>
Search.php
<?php
Require('config.php');
Include('functions.php')
$cats = Categories();
$post = "xx"; // default post value
IF (isset($_POST['Search'])) {
$post = htmlspecialchars(strip_tags(trim($_POST['term'])));
// build query
IF ( (!empty($post)) && (in_array($post, $cats)) ) {
$result = CategorySearch(true, $post);
}ELSE{
$result = "<p>Search option (".$post.") was invalid.</p>";
}
echo($result);
}
?>
<form action="search.php" name="search" method="post">
<select name="term"><?php echo(ddform_Categories($cats, $post))); ?></select>
<input type="text" class="form-control" placeholder="Search a Product">
<input type="submit" name="Search" value="Search" />
</form>
This is the PHP code of my main search section.
This search is working fine except in one case: When nothing is typed in the search box, it returns all values from the table.
How can I fix that?
<?php
mysql_connect("localhost","root","0392") or die("Could not connect");
mysql_select_db("emm") or die("could not connect");
$output="";
if(isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query=mysql_query("select name, code from employee_table where name LIKE '%$searchq%' or code LIKE '%$searchq%'");
$count = mysql_num_rows($query);
if($count == 0){
$output='No Matching Results Found !!';
}
else{
while($row = mysql_fetch_array($query)){
$name = $row['name'];
$code= $row['code'];
$output.="<a href='altprofile.php?cod=".$code."'><div class='col-md-3'><input type='text' name='nam' disabled='disabled' value='".$name."'></input></div></a> ";
}
}
}
echo($output);
?>
Just use
if(isset($_POST['searchVal']) && !empty($_POST['searchVal'])){
// DO code
}else{
echo "no results";
}
Try this
...
if(isset($_POST['searchVal']) && $_POST['searchVal'] != ''){
$searchq = $_POST['searchVal'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query=mysql_query("select name, code from employee_table where name LIKE '%$searchq%' or code LIKE '%$searchq%'");
$count = mysql_num_rows($query);
if($count == 0){
$output='No Matching Results Found !!';
}
else{
while($row = mysql_fetch_array($query)){
$name = $row['name'];
$code= $row['code'];
$output.="<a href='altprofile.php?cod=".$code."'><div class='col-md-`enter code here`3'>`enter code here`<input type='text' name='nam' `enter code here`disabled='disabled' value='".$name."'></input></div></a> ";
}
}
}
...
Note: Don't use mysql use mysqli or PDO
Just do the following two things,change if condition as
//checks value is not empty
if(isset($_POST['searchVal']) && !empty($_POST['searchVal']))
{
//all your stuff
}
else
{
echo "No results"
}
I have an issue where I need to be able to use check boxes in order to delete and modify data in a mysql database.
What is the most efficient way of being able to use multiple submit buttons to either insert data based on what the user types into the text boxes, delete based on the check boxes selected, and modify based on the check boxes selected.
Here is the code I have so far:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Auto,Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#############################################################################################
?>
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
<table width=50%>
<form method="post">
<table width border='0'>
<tr><td> Date:<input type="text" name="date"/></td>
<td>Ticket #:<input type="text" name="ticket"/></td></tr>
<table>
<tr><td>Description:<TEXTAREA COLS=50 name="description"></TEXTAREA></td></tr>
<tr><td> Result :<TEXTAREA COLS=50 name="result"></TEXTAREA></td></tr>
</table>
<tr><td><input type="submit" name="create" value="Add"/></td></tr>
<tr><td><input type="submit" name="delete" value="Delete"/></td></tr>
<tr><td><input type="submit" name="modify" value="Modify"/></td></tr>
</table>
</table>
<?php
print "<table width=80% border=1>\n";
$cols = 0;
while ($get_info = mysql_fetch_assoc($result)){
$id = $get_info['Auto'];
if($cols == 0)
{
$cols = 1;
print "<tr>";
print "<th>Select</th>";
foreach($get_info as $col => $value)
{
print "<th>$col</th>";
}
print "<tr>\n";
}
print "<tr>\n";
print "<td><input type='checkbox' name='selected[]' id='checkbox[]' value=$id></td>";
foreach ($get_info as $field)
print "\t<td align='center'><font face=arial size=1/>$field</font></td>\n";
print "</tr>\n";
}
print "</table>\n";
if (isset($_POST['create'])) {
$query_insert = "INSERT INTO ticket_history (Date, Ticket_Number, Description, Result)
VALUES ('$_POST[date]', '$_POST[ticket]', '$_POST[description]', '$_POST[result]')";
$result_insert = mysql_query($query_insert);
if ($result_insert) {
echo "win";
}
else {
echo "fail";
}
}
elseif (isset($_POST['delete'])) {
$ids = array();
foreach($_POST['selected'] as $selected) {
if (ctype_digit($selected)) {
$ids[] = $selected;
}
else {
die('invalid input');
}
$sql_delete = sprintf('DELETE FROM ticket_history WHERE Auto IN (%s)',
implode(',', $ids));
$result_delete = mysql_query($sql_delete);
}
if ($result_delete) {
echo $result_delete;
}
else {
echo "fail";
}
}
elseif (isset($_POST['modify'])) {
header('Location: modify_ticket.php');
}
mysql_close($conn);
?>
</form>
</BODY>
</HTML>
Insert.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query_insert = "INSERT INTO ticket_history (Date, Ticket_Number, Description, Result)
VALUES ('$_POST[date]', '$_POST[ticket]', '$_POST[description]', '$_POST[result]')";
$result_insert = mysql_query($query_insert);
if ($result_insert) {
echo "win";
}
else {
echo "fail";
}
#header( 'Location: ticket_history.php' );
?>
Delete.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#####################################
$ids = array();
foreach($_POST['selected'] as $selected) {
if (ctype_digit($selected)) {
$ids[] = $selected;
}
else {
die('invalid input');
}
$sql = sprintf('DELETE FROM ticket_history WHERE Auto IN (%s)',
implode(',', $ids));
$result = mysql_query($sql);
}
header( 'Location: ticket_history.php' );
?>
Any help is appreciated!
Thank you!
Another way to do it is your submit button's have the same name,
So:
<input type="submit" name="submit" value="Delete" />
<input type="submit" name="submit" value="Edit" />
PHP:
switch(strtolower($_POST['submit'])){
case "delete":
// delete logic
break;
case "edit":
// edit logic
break;
}
I would take the insert and delete code and put it on top of the main file instead of having them into files. the simplest way would be to submit the form to itself and based on the submit button clicked run the code block
if($_POST['create']){
// insert code
}
elseif($_POST['delete']){
// delete code
}
continue the logic of if/else/elseif to handle all the cases. This strikes me as the simplest way to get done what you want to do.
Edit:
Not sure but seems like you are handling the $_POST['create'] etc after the HTML code. You should always do that sort of processing BEFORE the html rendering and even before the query to get the records you want to display, this way your get query will always bring up to date results.
When you use multiple submit buttons, you can use PHP to determine which button was pressed. Based on this, you can have your application do different things with the data.
It's not clear what you want to accomplish with multiple buttons. Perhaps you could give more detail.
[Edit]
Looking over your code in detail, it is plain to see that it is quickly becoming a maintenance nightmare. Even if your app is tiny and you don't want to code use MVC pattern, you I still recommend using classes and separating presentation from application logic and from data access. Then it's much easier to maintain the application(fix bugs) and make changes.
If you are building anything more than a trivial script, I recommend using one of the excellent PHP frameworks:
http://framework.zend.com/
http://www.symfony-project.org/
http://codeigniter.com/
http://cakephp.org/
and many more: http://en.wikipedia.org/wiki/Comparison_of_web_application_frameworks#PHP
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Auto,Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#############################################################################################
if (isset($_POST['create'])) {
$query_insert = "INSERT INTO ticket_history (Date, Ticket_Number, Description, Result)
VALUES ('$_POST[date]', '$_POST[ticket]', '$_POST[description]', '$_POST[result]')";
$result_insert = mysql_query($query_insert);
if ($result_insert) {
echo "win";
}
else {
echo "fail";
}
}
elseif (isset($_POST['delete'])) {
$ids = array();
foreach($_POST['selected'] as $selected) {
if (ctype_digit($selected)) {
$ids[] = $selected;
}
else {
die('invalid input');
}
$sql_delete = sprintf('DELETE FROM ticket_history WHERE Auto IN (%s)',
implode(',', $ids));
$result_delete = mysql_query($sql_delete);
}
if ($result_delete) {
echo $result_delete;
}
else {
echo "fail";
}
}
elseif (isset($_POST['modify'])) {
header('Location: modify_ticket.php');
}
?>
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
<table width=50%>
<form method="post">
<table width border='0'>
<tr><td> Date:<input type="text" name="date"/></td>
<td>Ticket #:<input type="text" name="ticket"/></td></tr>
<table>
<tr><td>Description:<TEXTAREA COLS=50 name="description"></TEXTAREA></td></tr>
<tr><td> Result :<TEXTAREA COLS=50 name="result"></TEXTAREA></td></tr>
</table>
<tr><td><input type="submit" name="create" value="Add"/></td></tr>
<tr><td><input type="submit" name="delete" value="Delete"/></td></tr>
<tr><td><input type="submit" name="modify" value="Modify"/></td></tr>
</table>
</table>
I modified the code a little bit and THIS WILL WORK; however, it only works on the SECOND click.
When I select something and click DELETE, it will not delete, but when I do it again it will
Why is this? Thoughts?
Take the code for deletion and insertion above the select, so that the desired deletion of updation is done before you show the data.