I have a search field on my site that searches the database I use.
When I click on the search field and enter no text the search returns all results.
How can I have it so no results are returned if nothing is entered?
Is there any javascript that can help me?
Thanks!
James
<?php
$conn = mysql_connect("---", "", "");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
{
$search = "%" . $_POST["search"] . "%";
$searchterm = "%" . $_POST["searchterm"] . "%";
}
if (!mysql_select_db("weezycouk_641290_db1")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT name,lastname,email
FROM test_mysql
WHERE name LIKE '%".$search."%' AND lastname LIKE '%".$searchterm."%'";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if(document.getElementById('search').value == '')
return false;
if(document.getElementById('searchterm').value == '')
return false;
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo '<br>';
echo '<br>';
echo '<div class="data1">';
echo $row["name"];
echo '</div>';
echo '<br>';
echo '<div class="data2">';
echo $row["lastname"];
echo '</div>';
echo '<br>';
echo '<div class="data3">';
echo $row["email"];
echo '</div>';
}
mysql_free_result($result);
?>
Stop right there! SQL injection!
Your code has multiple SQL injection vulnerabilities. Fix them immediately!
Fixed? Let's go on.
Before deciding to perform the search, check if the search term is the empty string. If yes, do not perform the search. For example:
$search = // whatever the user typed; it's a good idea to trim() it
if(empty($search)) {
// return no results
}
else {
// do whatever you normally do
}
You could also perhaps change the search function (more likely, the search SQL query) to return no results if there's nothing to search for, which would basically let you move the above if "deeper inside" your code. IMHO it's best if the if stays here though, so I don't endorse this approach.
Taking care of details with Javascript: If your search is based on a form submission, it might be a good idea to prevent the submission entirely (with Javascript) if the search field is empty as a courtesy to the user. However, you should do this in addition to using the PHP check and not instead of it.
For an example in code, we 'd need to see your HTML.
For very basic control you can do something like that.
if(document.getElementById('searchField').value == '')
return false;
Either you can deny submitting the search form as long as nothing is filled in the search field using Javascript or you block the search in the according php file.
php:
if(empty($_GET['search'])){ // or whatever your field's name is
echo 'no results';
}else{
performSearch(); // do what you're doing right now
}
javascript using jQuery (if you use it):
$('#searchform').submit(function(){ // replace 'searchform' your form's id
return $('#search').val() != ''; // and 'search' with your search field's id
});
I wouldn't do this using JavaScript (as this can be turned off by the user).
I would do it using your server side language when you process the query.
e.g. in PHP something like this would work:
<?php
//processes
if (trim($_GET['search'])=='') {
//dont query anything
} else {
// do your query
}
//output
if (trim($_GET['search'])=='') {
?>
<p>Sorry, your search has returned no results.</p>
<?php
} else {
// output results
}
?>
Related
I wrote this code to comment system on my webpage. But i want to keep showing all data on web page while another people do comment and see another people's comment
include 'connection.php';
$con1= new connection();
$db=$con1-> open();
$qry= "INSERT INTO post (content) VALUES ('".$_POST["commentEntered"]."')";
$db->exec($qry);
if(isset($_POST['Submit'])) {
if ($con1->query($qry) === TRUE) {
echo "Your Comment Successfull Submited";
} else {
echo "Error: " . $qry . "<br>" . $con1->error;
}
$sql = 'SELECT * FROM post';
$q = $db->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
$con1->close();
}
if ($_POST)
echo "<h2> Your Comment Successfully Submitted</h2> <br> ".$_POST['commentEntered']."<br>";
}
?>
after your select, inside your if($_POST) write this
while ($row = $q->fetch()) {
foreach($row as $key=>$val){
if (!is_numeric($key)) echo "<p>$key=>$val</p>";
}
}
EDIT i'm not 100% sure you can close the connection and still do a ->fetch, (I think you can but i've never tried it) so you may have to move your connection close after this (but I think you'll be alright), also I am not sure if setFetchMode will return duplicate numbered keys or not so as a precaution I have filtered for them you may not need to
This problem should be simple to resolve, but I can't...
After a request, a condition has to verify if the concerned article really exists, verifying the URL ($_GET).
My code : ( a testing file with simple echos )
$id = $bdd->prepare('SELECT content FROM articles WHERE idArticle = ?');
$id->execute(array($_GET['numArticle']));
while ($dataID = $id->fetch()) {
if (empty($dataID) or $dataID == null or !isset($dataID)) {
echo 'No content';
} else {
echo 'Can load the page';
}
}
$id->closeCursor();
The page behaviour : "can load the page" is writing when numArticle is right, but if it is not, nothing appears, neither an error message or something.
Any idea/advice? Thank you.
One way to do this is by checking the number of rows returned by mysqli:
$id = $bdd->prepare('SELECT content FROM articles WHERE idArticle = ?');
$id->execute(array($_GET['numArticle']));
if($id->num_rows > 0){
echo "can load page";
}else{
echo 'No content';
}
You can use fetchAll() function of PDO then run a foreach loop on data:
$rows = $id->fetchAll(PDO::FETCH_ASSOC);
if(!empty($rows)){
foreach($rows as $row){
echo "content";
}
}
else{
echo "No Content";
}
Assuming you are using Pdo, it looks like you want to be using Pdo's fetchColumn method.
<?php
$stmt = $db->prepare('SELECT content FROM articles WHERE idArticle = ? LIMIT 1');
$stmt->execute(array($_GET['numArticle']));
if ($result = $stmt->fetchColumn()) {
echo 'A result';
} else {
echo 'Db fetch returned false (or could be a string that evaluates to false).';
}
What is the problem in my code ? every time it echo This image used as cover image , but delete query work properly.how can i fix it?
<?php
session_start();
if(!empty($_SESSION['userId']) && !empty($_SESSION['name'])){
include ('connect.php');
dbConnect();
if (isset($_GET['ximgid'])) {
$del=mysql_query("Delete FROM project_image WHERE ximgid='".$_GET['ximgid']."' And coverflag !='1'");
$delete=mysql_num_rows($del);
if($delete==1){
echo "<script type='text/javascript'>alert('Sucessfully Delete !!!')</script>";
echo "<script>javascript:window.location = 'projectImage.php'</script>";
}else{
echo "<script type='text/javascript'>alert('This Image Used As Cover Image')</script>";
echo "<script >window.location.href = 'projectImage.php'</script>";
}
}else{
echo "<script>javascript:window.location = 'index.php'</script>";
}
}
?>
mysql_num_rowsonly works with selectstatement.
For delete statements you have to use mysql_affected_rows
Here the part of the documentation of mysql_affected_rows:
Retrieves the number of rows from a result set. This command is only
valid for statements like SELECT or SHOW that return an actual result
set. To retrieve the number of rows affected by a INSERT, UPDATE,
REPLACE or DELETE query, use mysql_affected_rows().
mysql_affected_rows() is the way to go
$delete=mysql_affected_rows($del);
if($delete>0){
echo "<script type='text/javascript'>alert('Sucessfully Delete !!!') </script>";
echo "<script>javascript:window.location = 'projectImage.php'</script>";
}else if($delete==0){
echo "<script type='text/javascript'>alert('This Image Used As Cover Image')</script>";
echo "<script >window.location.href = 'projectImage.php'</script>";
}else{
echo "<script type='text/javascript'>alert('mysql error')</script>";
}
I had to solve my problem in an alternative way which is given below:
<?php
session_start();
if(!empty($_SESSION['userId']) && !empty($_SESSION['name'])){
include ('connect.php');
dbConnect();
if(isset($_GET['ximgid'])){
$selQuery = "SELECT coverflag FROM project_image WHERE ximgid ='".trim($_GET['ximgid'])."' AND zid = '1000' AND xpid = '".trim($_GET['pid'])."'";
$flagtResult=mysql_query($selQuery);
$flagRow=mysql_fetch_array($flagtResult);
mysql_free_result($flagRow);
$cover=$flagRow[0];
if($cover == 1){
echo "<script type='text/javascript'>alert('Used as cover picture')</script>";
echo "<script>javascript:window.location = 'projectImage.php'</script>";
}else{
$sql = "DELETE FROM project_image WHERE ximgid = '".trim($_GET['ximgid'])."' AND coverflag != '1' AND zid = '1000' AND xpid = '".trim($_GET['pid'])."'";
$result = mysql_query($sql) or die(mysql_error());
if($result > 0){
echo "<script type='text/javascript'>alert('Sucessfully Detele !!!')</script>";
echo "<script>javascript:window.location = 'projectImage.php'</script>";
}
}
}
}else{
echo "<script>javascript:window.location = 'index.php'</script>";
}
?>
Now I can get my proper output.. Thanks Everyone.
first of all it appears that you are escaping ximgid and coverflag with ' which would throw a syntax error in your sql if those were not varchar fields.
$del=mysql_query("Delete FROM project_image WHERE ximgid=".$_GET['ximgid']." And coverflag !=1;");
Second issue to address would be that you are taking a $_GET parameter and putting it directly into your SQL query which is just trouble looking to happen so I would suggest next changing it to:
$del=mysql_query("Delete FROM project_image WHERE ximgid=".mysql_real_escape_string($_GET['ximgid'])." And coverflag !=1;");
if you need extra help debugging your SQL you can always temporarily put a call to
echo mysql_error();
after your call to mysql_query in order to show the error message from the server.
i've got a problem with my php script. I want to check my script if there is anything in array and if there's no to echo a message but when array is empty it just don't echo nothing.
That's my code:
include("mysql_connect.php");
$name = $_POST['playerName'];
$users = mysql_query('SELECT * FROM playerdata WHERE username LIKE "'.$name.'%"');
if($name==""){
echo 'Type in player name!';
}else{
while($usersList= mysql_fetch_assoc($users)){
if(!array_count_values($usersList)){
echo 'Player not found';
}else{
echo $usersList['username'].', ';
}
}//While end.
}//If name is empty end.
As mentioned, you have to check for rows before the loop.
$rows = mysql_num_rows($users);
if($rows==0) echo "No rows..";
else {
foreach() {
The problem seems is that, if a user enters a invalid name, the while loop does not execute, as the query simply cannot find any rows, the code should be as follows
include("mysql_connect.php");
$name = $_POST['playerName'];
if( $name === "" ){
echo 'Type in player name!';
} else {
$users = mysql_query('SELECT * FROM playerdata WHERE username LIKE "'.$name.'%"');
if ( mysql_num_rows($users) == 0) {
echo "Invalid Player name provided";
} else {
while($usersList= mysql_fetch_assoc($users)){
{
echo $usersList['username'].', ';
} //While end.
}
}//empty name
Notes:
I have re-formatted the code as it looked ugly
The query is executed only if a user provides some text for name, why execute the query when the name is empty !
instead of
if(!array_count_values($usersList)){
use
if(empty($usersList)){
Your while loop wont be executed if $users is empty, so the condition:
if(!array_count_values($usersList)){
echo 'Player not found';
}
will never be met because it is contained in a loop which will never run.
I use this code to select password field from the sql server 2012 db, and does not return any data
I tried to change the field type and it did work
actually I can't change the field type in the main server and I need to work with it as it is
any idea how to work around it?
<?php
$objConnect = mssql_connect("localhost:1434\MSSQLSERVER","fdi","fdifdi");
if($objConnect)
{
echo "Database Connected.<br />";
mssql_select_db('Intranett', $objConnect);
$query = mssql_query('SELECT [pass] FROM [Intranett].[dbo].[v24Brukere]');
// Check if there were any records
if (!mssql_num_rows($query)) {
echo 'No records found';
} else {
// Print a nice list of users in the format of:
// * name (username)
echo '<ul>';
while ($row = mssql_fetch_object($query)) {
echo '<li>' . $row->pass .' </li>';
}
echo '</ul>';
}
}
else
{
echo "Database Connect Failed.<br />";
echo mssql_get_last_message();
}
mssql_close($objConnect);
?>
As far as I know, NVARCHAR is not supported with the old and long outdated mssql-drivers. You should instead use Microsoft's SQL Server Driver for PHP.