I want to perform a search from the database using php in which when i enter name arun it should search for name arun and display the result with name arun and when i enter name and email it should search for name and email and should display single result since the email is unique field i have written the following code but it is not working can someone help me?
Please add a comment if any one gives Downvote and Why?
<?php
if (isset($_SESSION['message11'])) {
echo $_SESSION['message11'];
unset($_SESSION['message11']);
}
?>
<?php
include('connection.php');
$name = $_POST['name'];
$email = $_POST['email'];
$qualification = $_POST['qualify'];
$sql = "SELECT * FROM form WHERE Name ='$name' OR EmailAddress = '$email' OR Qualification = '$qualification' ";
$result = $conn->query($sql);
if (!empty($_POST)) {
if ($result->num_rows === 0) {
echo '<p style="margin-left:340px">no records</p>';
}
}
while ($row = $result->fetch_assoc()) {
$_SESSION["snum"] = $row['sno'];
$_SESSION["nam"] = $row['Name'];
$_SESSION["quali"] = $row['Qualification'];
$_SESSION["emai"] = $row['EmailAddress'];
echo '<br>';
echo '<form name="friend" action="received.php" method="post">';
echo '<input style="margin-left:340px;padding-bottom:10px" type="checkbox" value="' . $row['sno'] . '" name="friend[]"> user Details</input>';
echo '<br>';
echo '<br>';
echo '<div class="container" style="border-style:solid; border-width:medium;width: 550px;">';
echo '<br>';
echo 'Name: ' . $row['Name'];
echo '<br /> EmailAddress: ' . $row['EmailAddress'];
echo '<br /> Qualification: ' . $row['Qualification'];
echo '<br /> DOB: ' . $row['DOB'];
echo '<br/>';
echo '<br/>';
echo '<br/>';
echo '<br/>';
echo '</div>';
echo '<br/>';
}
if (!empty($_POST)) {
echo '<button style="margin-left:340px" type=""submit">invite</button>';
}
echo '</form>';
$conn->close();
?>
You are adding OR condition to three fields even if they are not entered by the user.
Use conditions so that sql should search only entered fields.
Use array()
$sql = "SELECT * FROM form WHERE ";
$conditions = array();
if (! empty($name)) {
$conditions[] = "Name ='$name'";
}
if (! empty($email)) {
$conditions[] = "EmailAddress ='$email'";
}
if (! empty($qualification)) {
$conditions[] = "Qualification ='$qualification'";
}
$sql .= ! empty($conditions) ? implode(' OR ', $conditions) : '1';
$result=$conn->query($sql);
Try this LIKE will be effective for searching stuffs.
Simple and best practice.
SELECT * FROM form WHERE Name LIKE '%".$name."%' OR EmailAddress LIKE '%".$email."%' OR Qualification LIKE '%".$qualification."%'
I have a little Problem with my Update query to chnage the Profile Infos
Problem now:
My Update Query is not working completly, the E-Mail query work but the status query is not working.
PHP CODE
if(!empty($_POST)) {
$query = "UPDATE users SET";
if(!empty($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) && $_POST['email'] != $_SESSION['u']['email']) {
$s_mail = $_POST['email'];
$row = mysql_num_rows(mysql_query("SELECT email FROM users WHERE email='$s_mail'"));
if($row != 0) {
header("Location: ".$l['settings']."?msg=2");
die("REDIRECT");
}
$query .= " `email`='".$_POST['email']."'";
$_SESSION['u']['email'] = $_POST['email'];
} else if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
header("Location: ".$l['settings']."?msg=3");
die("REDIRECT");
}
//PROBLEM starts here
if(!empty($_POST['status'])) {
$query .= ",`status`='".$_POST['status']."'";
$_SESSION['u']['status'] = $_POST['status'];
}
//AND ends here
$query .= " WHERE id='".$_SESSION['u']['id']."'";
mysql_query($query);
header("Location: ".$l['settings']."?msg=1");
die("REDIRECT");
}
HTML FORM
<input maxlength="200" type="text" class="form-control" placeholder="Status" name="status" value="<?php //ECHO STATUS ?>" />
Maybe someone can help me.
On your $query you have
$query .= ",`status`='".$_POST['status']."'";
remove comma make it like this
$query .= " `status`='".$_POST['status']."'";
You need to set a flag for email condition as
$flag = FALSE;// set a flag
if (!empty($_POST)) {
if (!empty($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) && $_POST['email'] != $_SESSION['u']['email']) {
$s_mail = $_POST['email'];
$row = mysql_num_rows(mysql_query("SELECT email FROM users WHERE email='$s_mail'"));
if ($row != 0) {
header("Location: " . $l['settings'] . "?msg=2");
die("REDIRECT");
}
$flag = TRUE;// set to true if success
$_SESSION['u']['email'] = $_POST['email'];
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
header("Location: " . $l['settings'] . "?msg=3");
die("REDIRECT");
}
//PROBLEM starts here
if (!empty($_POST['status'])) {
$query = "UPDATE users SET";
$query .= " `status`='" . $_POST['status'] . "'";
if ($flag) {// if true then apply email condition
$query .= ",`email`='" . $_POST['email'] . "'";
}
$query .= " WHERE id='" . $_SESSION['u']['id'] . "'";
$_SESSION['u']['status'] = $_POST['status'];
}
//AND ends here
mysql_query($query);
header("Location: " . $l['settings'] . "?msg=1");
die("REDIRECT");
}
Note:- mysql is deprecated instead use mysqli OR pdo
so i'm still relatively new to PHP and have been building a order form that can validate the fields before sending, as well as checking for spam.
From testing the below code works fine in returning errors and so on, but when I enter correct information I dont get any emails.
It was working fine before i added the Vaildation part to it but now im getting the problem above. Again i am still learning so any pointers would be nice, thanks
<?php
function spamcheck($field) {
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
return TRUE;
} else {
return FALSE;
}
}
?>
<?php
if (!isset($_POST["submit"])) {
?>
Form
<?php }
else
{
if (isset($_POST["email"])) {
$mailcheck = spamcheck($_POST["email"]);
if ($mailcheck==FALSE) {
echo "Invalid input";
}
//field vailation
else {
if (isset($_POST['submit'])) {
$errors = array();
if (!empty($_POST["fullname"])) {
$fullname = $_POST["fullname"];
$pattern = "/^[a-zA-Z0-9\_]{2,20}/";
if (preg_match($pattern,$fullname)){ $fullname = $_POST["fullname"];}
else{ $errors[] = 'Your Name can only contain _, 1-9, A-Z or a-z 2-20 long.';}
} else {$errors[] = 'You forgot to enter your First Name.';}
if (!empty($_POST["contact"])) {
$contact = $_POST["contact"];
$pattern = "/^[0-9\_]{6,20}/";
if (preg_match($pattern,$contact)){ $contact = $_POST["contact"];}
else{ $errors[] = 'Your contact number can only be numbers, or is too short';}
} else {$errors[] = 'You forgot to enter your contact number.';}
}
//end vaildation
else{
$fullname = $_POST["fullname"];
$email = $_POST["email"];
$address = $_POST["address"];
$address2 = $_POST["address2"];
$town = $_POST["town"];
$postcode = $_POST["postcode"];
$contact = $_POST["contact"];
$shipping = $_POST["shipping"];
$extra = $_POST["extra"];
$extra = wordwrap($extra, 70);
$message = '
Full Name: ' . $fullname . '
Delivery Address: ' . $address . '
Delivery Address2: ' . $address2 . '
Town/City: ' . $town . '
Postal Code: ' . $postcode . '
Contact: ' . $contact . '
Email Address: ' . $email . '
Special instructions: ' . $extra . '
Shipping Method: ' . $shipping . '
';
mail("myemail#myaddress.com","Order form",$message,"email: $email\n");
echo
"<html>
<body><br><br>
Order successful, we will be in contact shortly<br>
</body>
</html>";
}
}
}
}
?>
<?php
if (isset($_POST['submit'])) {
if (!empty($errors)) {
echo '<hr /><h3>The following occurred:</h3><ul>';
foreach ($errors as $msg) { echo '<li>'. $msg . '</li>';}
echo '</ul><h3>Your mail could not be sent due to input errors.</h3><hr />';}
else{echo
"<html>
<body><br><br>
Order successful, we will be in contact shortly<br>
</body>
</html>";
}
}
?>
After using error_reporting(E_ALL); ive noticed that im getting an error unexpected 'else' (T_ELSE) for the else at the top of the second block of code, so I tried moving code to :
<?php
error_reporting(E_ALL);
if (!isset($_POST["submit"])) {
}
else
{
And left the form above this so that when the sumbit button is pressed the forms wont dissapear. Which is not giving me any errors but still not email once submitted
I have been designing a website and everything has been working perfectly, until I started adding in little extras so it would work EXACTLY how I wanted it to work.
This is the script for a website that uploads a title, description, name of a person, image, email address and password for the advert that they are putting online. However it no longer wants to correctly name the image and it sends out an email twice, once in the instance that there may be an image and it instantly does it in the instance where someone may not upload an image, but it is reading it as if it is doing both because there is an error with the file upload.
Btw this is the first PHP script I have ever created so it may seem mashy as I have been kind of mixing it up from different things that I have found online :)
p.s the page where the magic happens is www.afterswap.com/give.php
p.p.s I have a global config file that sets all of the DB connection info etc, hence it being non-existent here.
<?PHP
include("inc/header.php");
foreach ($_POST as $key => $val)
$_POST[$key] = mysqli_real_escape_string($con, $val);
$back = "<a href='give.php'>Click Here To Go Back And Try Again</a>";
if (isset($_POST['upload']) && $_FILES['userfile']['size'] > 0) {
$title = mysqli_real_escape_string($title123);
$title123 = mysqli_real_escape_string($_POST['title']);
$description = mysqli_real_escape_string($description123);
$description123 = mysqli_real_escape_string($_POST['description']);
$Sell_by = $_POST['Sell_by'];
$name = mysqli_real_escape_string($name123);
$name123 = mysqli_real_escape_string($_POST['name']);
$email = $_POST['email'];
$password = $_POST['password'];
$imagename = basename($_FILES['userfile']['name']);
$uploadedfile = $_FILES['userfile']['tmp_name'];
if (empty($imagename)) {
$error = 1;
echo "<h2 class='error'>The name of the image was not found.</h2>" . $back;
}
if ($error != 1 && $noimg != 1) {
$filename = stripslashes($_FILES['userfile']['name']);
$extension = substr(strrchr($filename, '.'), 1);
$extension = strtolower($extension);
}
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
echo '<h2 class="error">Error. Images Must Be Jpg, Gif, or Png Format! Please Go Back And Try Another Image.</h2>' . $back . '';
$errors = 1;
} else {
$time = time();
$newimage = "/photos/" . $time . $imagename;
$result = move_uploaded_file($_FILES['userfile']['tmp_name'], $newimage);
if (empty($result)) {
$error = 1;
echo "<h2 class='error'>There was an error uploading your image.</h2><br/>" . $back . "";
}
$date = date("Y/m/d H:i:s");
$query = "INSERT INTO classifieds (adid, title, description, Sell_by, name, email, password, picture, date, views, authorized ) VALUES ('', '$title123', '$description123', '$Sell_by', '$name123', '$email', '$password', '$newimage', '$date', '0', '0')";
mysqli_query($query) or die(mysqli_error());
$pullback = "SELECT * FROM classifieds WHERE title = '$title123' AND email ='$email' limit 1";
$query2 = mysqli_query($pullback) or die(mysqli_error());
while ($row = mysqli_fetch_array($query2, MYSQL_ASSOC)) {
$newid = $row['adid'];
$pass = $row['pass'];
}
$url = "http://";
$url .= getenv("HTTP_HOST");
$Name = "AfterSwap";
$emailf = "noreply#afterswap.com";
$recipient = $email;
$mail_body = "Thank you for posting a new listing!<br /><br />You May Now Manage Your Ad by selecting one of the following options:<br /><br />Approve your listing: <a href='" . $url . "/approve.php?id=" . $newid . "&pass=" . $password . "'>Click Here</a><br/>Edit your listing: <a href='$url/edit.php?id=" . $newid . "&pass=" . $password . "'>Click Here</a><br/>Remove your listing: <a href='" . $url . "/remove.php?id=" . $newid . "&pass=" . $password . "'>Click Here</a><br /><br />Regards,<br /><br />The AfterSwap Team";
$subject = "AfterSwap Ad Details";
$headers = "From: " . $Name . " <" . $emailf . ">\r\n";
$headers .= "Content-type: text/html\r\n";
mail($recipient, $subject, $mail_body, $headers);
echo "<div align='justify'><div class='success'>Your listing '" . $name123 . "' Has Been Submitted Successfully! <br/><br/>Please take note: Your listing will not show on the website until you verify it via the email sent to you. This email also allows you to edit and remove your listing as well.</div></div>";
}
} elseif (isset($_POST['upload'])) {
$title = mysqli_real_escape_string($title123);
$title123 = mysqli_real_escape_string($_POST['title']);
$description = mysqli_real_escape_string($description123);
$description123 = mysqli_real_escape_string($_POST['description']);
$Sell_by = $_POST['Sell_by'];
$name = mysqli_real_escape_string($name123);
$name123 = mysqli_real_escape_string($_POST['name']);
$email = $_POST['email'];
$password = $_POST['password'];
$date = date("Y/m/d H:i:s");
$query = "INSERT INTO classifieds (adid, title, description, cat, Sell_by, name, email, password, picture, date, views, authorized ) VALUES ('', '$title123', '$description123', '$category', '$Sell_by', '$name123', '$email', '$password', 'images/noimage.jpg', '$date', '0', '0')";
mysqli_query($query) or die(mysqli_error());
$pullback = "SELECT * FROM classifieds WHERE title = '$title123' AND email ='$email' limit 1";
$query2 = mysqli_query($pullback) or die(mysqli_error());
while ($row = mysqli_fetch_array($query2, MYSQL_ASSOC)) {
$newid = $row['adid'];
$pass = $row['pass'];
}
$url = "http://";
$url .= getenv("HTTP_HOST");
$Name = "AfterSwap";
$emailf = "noreply#afterswap.com";
$recipient = $email;
$mail_body = "Thank you for posting a new listing!<br /><br />You May Now Manage Your Ad by selecting one of the following options:<br /><br />Approve your listing: <a href='" . $url . "/approve.php?id=" . $newid . "&pass=" . $password . "'>Click Here</a><br/>Edit your listing: <a href='$url/edit.php?id=" . $newid . "&pass=" . $password . "'>Click Here</a><br/>Remove your listing: <a href='" . $url . "/remove.php?id=" . $newid . "&pass=" . $password . "'>Click Here</a><br /><br />Regards,<br /><br />The AfterSwap Team";
$subject = "AfterSwap Ad Details";
$headers = "From: " . $Name . " <" . $emailf . ">\r\n";
$headers .= "Content-type: text/html\r\n";
mail($recipient, $subject, $mail_body, $headers);
echo "<div align='justify'><div class='success'>Thank you " . $name123 . ", your listing has been submitted successfully! <br/><br/>Please take note: Your isting will not show on the website until you verify it via the email sent to you. This email also allows you to edit and remove your listing as well.</div></div>";
} else {
?>
/* HTML Form here */
<?PHP } ?>
Try this
Change this line
} elseif (isset($_POST['upload'])) {
to
} elseif (isset ( $_POST ['upload'] ) && empty($_FILES)) {
The only thing I can think of would be a if, elseif, or else being passed twice because the condition is being met twice. You may want to revise the code with better indentation, and checking when the elseif, if, and else blocks are passed. Also, it would be a really good idea to take the advice from the two people that commented on your post, MYSQLI is a great way to go! One more thing: You should never pass $_POST unsanitized!! Here is a short easy sanitization script!
MYSQLI:
foreach($_POST as $key=>$val)
$_POST[$key] = mysqli_real_escape_string($con, $val);
MYSQL:
foreach($_POST as $key=>$val)
$_POST[$key] = mysql_real_escape_string($con, $val);
So I have this login php script that I am using and it works fine on one server (returns "success" || "invalid login") and then this other server it breaks because it returns a line break and then "success" or "invalid login"
My guess is a php.ini setting. I am just not sure which one.
<?php
include("../config.php");
include("../connect.php");
$adminCheck = mysql_query("SELECT * FROM admins WHERE username = '" . mysql_real_escape_string($_POST['username']) . "' AND password = '" . mysql_real_escape_string($_POST['password']) . "'");
if (mysql_num_rows($adminCheck) == 1)
{
$result = mysql_fetch_array($adminCheck);
$_SESSION['user']['level'] = "admin";
$_SESSION['user']['userid'] = $result['id'];
$_SESSION['user']['username'] = $result['username'];
echo "success";
}
else
{
$clientCheck = mysql_query("SELECT * FROM clients WHERE username = '" . mysql_real_escape_string($_POST['username']) . "' AND password = '" . mysql_real_escape_string($_POST['password']) . "'");
if (mysql_num_rows($clientCheck) == 1)
{
$result = mysql_fetch_array($clientCheck);
$_SESSION['user']['level'] = "client";
$_SESSION['user']['userid'] = $result['id'];
$_SESSION['user']['username'] = $result['username'];
$_SESSION['user']['client'] = $result['client'];
echo "success";
}
else
{
echo "invalid login";
}
}
?>
I'd bet you a coke that connect.php or config.php contain a \n (or \r\n) before or after their <?php ?> parts.
This is most likely due to your includes. The code you posted has no reason to have one, and there is no php.ini setting that I'm aware of to add such.
Post your config and connect (with username/pw hidden) for us to help further.
The code displayed does not indicate the occurrence of a line-break.
On a side note since you are only outputting one value from your booleans then you could initialize a variable to hold the response and then only echo the response once:
<?php
include("../config.php");
include("../connect.php");
$response = 'success';
$adminCheck = mysql_query("SELECT * FROM admins WHERE username = '" . mysql_real_escape_string($_POST['username']) . "' AND password = '" . mysql_real_escape_string($_POST['password']) . "'");
if (mysql_num_rows($adminCheck) == 1)
{
$result = mysql_fetch_array($adminCheck);
$_SESSION['user']['level'] = "admin";
$_SESSION['user']['userid'] = $result['id'];
$_SESSION['user']['username'] = $result['username'];
}
else
{
$clientCheck = mysql_query("SELECT * FROM clients WHERE username = '" . mysql_real_escape_string($_POST['username']) . "' AND password = '" . mysql_real_escape_string($_POST['password']) . "'");
if (mysql_num_rows($clientCheck) == 1)
{
$result = mysql_fetch_array($clientCheck);
$_SESSION['user']['level'] = "client";
$_SESSION['user']['userid'] = $result['id'];
$_SESSION['user']['username'] = $result['username'];
$_SESSION['user']['client'] = $result['client'];
}
else
{
$response = "invalid login";
}
}
echo $response;
?>