I'm trying to create a filter in mysql and php. In my database, I have many fields like : name, phoneNumber, email... And even if I do something like
if(!empty($_POST['name'])){
$name=$_POST['name']
}
if(!empty($_POST['phoneNumber'])){
$phoneNumber= $_POST['phoneNumber']
}
if(!empty($_POST['email'])){
$email=$_POST['email']
}
If someone only enters the name field, how do I do to not include the other fields in the query?
$query=query("SELECT * FROM clients WHERE clientName=$clientName && phoneNumber=$phoneNumber && email=$email)
you can try something like given below
if(!empty($_POST['name'])){
$name=$_POST['name'];
$query="SELECT * FROM clients WHERE clientName='$name'";
}
if(!empty($_POST['phoneNumber'])){
$phoneNumber= $_POST['phoneNumber'];
$query.= " AND phoneNumber='$phoneNumber'";
}
if(!empty($_POST['email'])){
$email=$_POST['email'];
$query.= " AND email='$email'";
}
NOTE:use prepared query because this is open to sql injection attack.
this is demonstration only.
What I do for this sort of thing is have all the search terms sent to post within a single JSON object. So in javascript I collect all the search inputs and have an object where each key corresponds to the name of the input and each value corresponds to the val. For example in jQuery
var searchObj = {};
$(".searchInput").each(function() {
searchObj[$(this).attr('name')] = $(this).val();
});
var searchJSON = JSON.stringify(searchObj);
//later send searchJSON to php
//in php
$seachObj = json_decode($_POST["searchJSON"], true);
$sql = "SELECT * in CLIENTS WHERE ";
foreach($searchObj as $key => $val) {
$sql .= "$key = '$val' AND ";
}
$sql .= "1";
NOW THIS IS TOTALLY UNSECURED!!! Only included so that it's clear. Better to use PDO or mysqli, to use prepared statements. Like this:
$seachObj = json_decode($_POST["searchJSON"], true);
$sql = "SELECT * in CLIENTS WHERE ";
$vals = [];
foreach($searchObj as $key => $val) {
$vals[] = $val;
$sql .= "$key = ? AND ";
}
$sql .= "1";
//learn more about PDO to get this part
$stmt = $pdo->prepare($sql);
$stmt->execute($vars);
I think this would do it.
$condition = "";
if(!empty($_POST['name'])){
$name=$_POST['name'];
$condition .= " AND clientName LIKE ".$name;
}
if(!empty($_POST['phoneNumber'])){
$phoneNumber= $_POST['phoneNumber'];
$condition .= " AND phoneNumber ='".$phoneNumber."'";
}
if(!empty($_POST['email'])){
$email=$_POST['email'];
$condition .= " AND email='".$email."'";
}
if(!empty($condition)){
$query="SELECT * FROM clients WHERE ".ltrim($condition," AND");
}else{
$query="SELECT * FROM clients";
}
Related
code:
if(isset($_POST["add"]))
{
extract($_POST);
$facilities = $_POST['facilities'];
$chk="";
foreach($facilities as $chk1)
{
$chk .= $chk1.",";
}
$exam = $_POST['exam'];
$chks="";
foreach($exam as $chked)
{
$chks .= $chked.",";
}
$filename = $_FILES['college_image']['name'];
$path = "college_banner/";
$move=move_uploaded_file($_FILES['college_image']['tmp_name'],$path.$_FILES['college_image']['name']);
$filename2 = $_FILES['logo']['name'];
$path2 = "college_logo/";
$move=move_uploaded_file($_FILES['logo']['tmp_name'],$path2.$_FILES['logo']['name']);
echo "insert into all_colleges(college_name,establish,approve,affiliated,address,website,about_us,city,courses,logo,college_image,phone,field,tag,video1,video2,facilities,courses_fee,short_name,state,exams,form_fee,college_commission,client_commission,form_type)values('$name','$establish','$approve','$affiliated','$address','$website','$about_us','$city','$course','$filename2','$filename','$phone2','$field','$tag','$video1','$video2','$chk','$fee','$short','$state','$chks','$form_fee','$college_commission','$client_commission','$form_type')";
$result = mysqli_query($link,$sql2);
if($result == true)
{
$msg .= "<h5 style='color:green;'>Successfull</h5>";
}
else
{
$msg .= "<h5 style='color:red;'>Error</h5>";
}
}
In database I have an auto_increment id i.e. college_id but when I remove auto_increment over college_id then it show successfull message when click on add button instead of error. So, how can I fix this problem ?
Thank You
It doesn't matter with you college_id just make sure if it is AUTO_INCREMENT then it must be PRIMARY KEY.
And in SQL query you are not assigning query to your $sql2 variable so use
echo $sql2 = "insert into all_colleges ...";
//---^ assign query in $sql2
$result = mysqli_query($link,$sql2); // <-- you are passing $sql2
1 more thing you can use implode() without using loops for checked values in a single statement like,
$chk= = implode(',',$_POST['facilities']);
I am currently working on this project. Data can be retrieved from database with this code, if certificateNumber is numeric, but it does not search person if certificateNumber field has alphanumeric data.
Where am I wrong with this?
<?php
$flag = 0;
$reg=$_REQUEST["cerf"];
echo ($reg);
$con = mysqli_connect('localhost','neoncom_db','12345','neoncom_std');
$qur = 'select * from student where certificateNumber = '.$reg;
$check = mysqli_query($con,$qur);
while($row=mysqli_fetch_array($check))
{
if($reg==$row["certificateNumber"])
{
$flag++;
$first = $row["first"];
$last=$row["last"];
$num = $row["certificateNumber"];
$name = $first ." ".$last;
$course = $row["course"];
$date = $row["signupDate"];
echo($row["certificateNumber"]);
echo($row["first"]);
echo($row["last"]);
}
}
if(count==0)
{
echo("NOT FOUND");
}
?>
You need to encapsulate $reg in quotes. So your query string $qur should be like this:
$qur = "select * from student where certificateNumber = '" . $reg . "'";
Sidenote: Learn about prepared statement because right now your query is susceptible to SQL injection attack. Also see how you can prevent SQL injection in PHP.
I'm attempting to construct an MySQL query around some optional search parameters in PHP. There are 3 search fields linking to the three columns in my database. The user should be able to search each column individually, or up to all 3 if they want to narrow down their results.
My PHP code is built so that the if one of the search fields is empty, it doesn't matter and it will continue the search in the other two fields. However, I'm struggling to get my head around how to construct my SQL query afterwards as my where clauses have already been specified in the $whereclauses array. I am returning the same columns in any search the user makes so that should make the SQL query quite simple and mean it only needs to be defined once.
My PHP code:
<?php
require '../db/connect.php';
$whereclauses = array();
$subsets = false;
// for every field
if(!empty($_POST['name']))
{
$subsets = true;
$whereclauses[] = " ARTIST = ". mysql_real_escape_string(trim($_POST['name']));
}
if($subsets)
{
$whereclauses = implode(", ". $whereclauses);
}
else
{
$whereclauses ="";
}
SQL query in PHP
if(!empty($whereclauses)) {
$sql = "SELECT
`ARTIST`, `TRACKTITLE`, `DATE`, `LOCATION`
FROM
`table 3`";
};
$result = mysql_query($sql);
$data = array();
while ($array = mysql_fetch_assoc($result)) {
$data[] = $array;
}
header('Content-type: application/json');
echo json_encode($data);
How can I add the $whereclauses array into my $sql query?
<?php
require '../db/connect.php';
$whereclauses = array("where 1=1");
$subsets = false;
// for every field
if(!empty($_POST['name']))
{
$subsets = true;
$whereclauses[] = " ARTIST = '". mysql_real_escape_string(trim($_POST['name']))."'";
}
Just implode the array in sql
$sql = "SELECT
`ARTIST`, `TRACKTITLE`, `DATE`, `LOCATION`
FROM
`table 3` ".implode(" AND ",$whereclauses);
if(!empty($whereclauses)) {
$sql = "SELECT
`ARTIST`, `TRACKTITLE`, `DATE`, `LOCATION`
FROM
`table 3`";
$sql.= " WHERE 1=1 ";
foreach($whereclauses as $where){
$sql.= " AND ".$where;
}
}
$result = mysql_query($sql);
$data = array();
while ($array = mysql_fetch_assoc($result)) {
$data[] = $array;
}
header('Content-type: application/json');
echo json_encode($data);
I have a form with two fields. The user can fill in either one or both and the MySQL database should be queried accordingly.
Here is my php code:
$number1 = $_POST['number1'];
$number2= $_POST['number2'];
$set = FALSE;
$query = "SELECT * FROM table";
if (!empty($number1 ))
{
$query .= " WHERE number1 = ".$number1."";
$set = TRUE;
}
if (!empty($number2))
{
$query .= ($set===TRUE ? " AND" : " WHERE") . " number2 = ".$number2."";
}
$data = mysql_query($query) or die("Couldn't execute query. ". mysql_error());
The code works fine if either number1 or both of the fields are filled in. However when only the second field is filled in I get the error:
Couldn't execute query. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
If I echo the query it is shown correctly:
SELECT * FROM table WHERE number2 = entered value
Any help is much appreciated! Thanks!!
have you forget escape values? u can use somthing like this
$fields = array();
if(!empty($_POST['number1'])) {
$fields[] = 'number1='.mysqli_real_escape_string($_POST['number1']);
}
if(!empty($_POST['number2'])) {
$fields[] = 'number2='.mysqli_real_escape_string($_POST['number2']);
}
$sql = "SELECT * FROM table WHERE ".implide(" AND ", $fields);
$data = mysqli_query($query) or die("Couldn't execute query. ". mysql_error());
mysql extension is deprecated, use mysqli instead
try this
$number1 = $_POST['number1'];
$number2= $_POST['number2'];
$set = FALSE;
$query = "SELECT * FROM table";
if (!empty($number1 ))
{
$query .= " WHERE number1 = ".$number1."";
$set = TRUE;
}
if (!empty($number2))
{
if($set==FALSE)
$query .= " WHERE number2 = ".$number2;
else
$query .= " AND number2 = ".$number2;
}
I think you get the error because of the assignment. You wrote $set===TRUE, its == not ===
The error is here:
if (!empty($number2))
{
$query .= ($set===TRUE ? " AND" : " WHERE") . " number2 = ".$number2."";
}
My script is quitting on SQL calls that should not have an issue. One of the queries that is failing to update is:
UPDATE dist_comp.private_schools SET mail_address = '1351 Royalty Dr', city = 'Alabaster', state = 'AL',zip_code = 35007,phone = '2056633973' WHERE school_name = 'Kingwood Christian School' AND city = 'Alabaster'
When I run the same query in MySQL workbench, I get
Error Code: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column To disable safe mode, toggle the option in Preferences -> SQL Queries and reconnect.
Is this the reason why my script is quitting?
<?php
require_once('connect.php');
function schoolInfo($school_name,$city){
$data = array();
$counter = 0;
$handle = fopen("k12privateschools_loc_0813.csv","r") or exit('doesnt work');
fgetcsv($handle) or exit('fgetcsv issue');
while( ($line = fgetcsv($handle)) !== false) {
$data[] = $line;
///echo ("Does schoolname and city match: " . addslashes($data[$counter][2]). ":" . $school_name . " ; " . addslashes($data[$counter][4]). ":" . $city . "\n");
if (addslashes($data[$counter][2])==$school_name && addslashes($data[$counter][4])==$city){
//echo ('match');
if($data[$counter][13] != ""){
$mail_address = $data[$counter][12];
$city= $data[$counter][13];
$state= $data[$counter][14];
$zip_code= $data[$counter][15];
$zip_4= $data[$counter][16];
}else{
$mail_address = $data[$counter][3];
$city= $data[$counter][4];
$state= $data[$counter][5];
$zip_code= $data[$counter][6];
$zip_4= $data[$counter][7];
}
$phone= $data[$counter][8];
$query= "UPDATE dist_comp.private_schools SET
mail_address = '".$mail_address."',
city = '".$city."',
state = '".$state."',";
if($zip_code != ""){
$query.="zip_code = ".$zip_code.",";
}
if($zip_4 != ""){
$query.="zip_4 = ".$zip_4.",";
}
$query.= "phone = '".$phone."'
WHERE school_name = '".$school_name."' AND city = '" .$city . "'";
mysqli_query($con,$query);
if(mysqli_affected_rows($con)==0){
exit($query . "\n ");
}
//echo $query;
}//end if counter \
else{
//echo("no match");
}
$counter++;
}//end read lines from file
}
echo "starting import \n";
//Query for all school names
$sql2 = mysqli_query($con,"SELECT school_name,city FROM dist_comp.private_schools") or exit('query issue second');
while($row = mysqli_fetch_array($sql2)){ //this line is making it take a really long time
$school_name= addslashes($row['school_name']);
$city = addslashes($row['city']);
schoolInfo($school_name,$city);
}//end while fetch array
//}
echo "Import finished";
?>
Try to disable safe update using this line before your query :
mysqli_query($con,"SET sql_safe_updates=0");
Or use :
$query="SET sql_safe_updates=0";
$query.= "UPDATE dist_comp.private_schools SET
mail_address = '".$mail_address."',
city = '".$city."',
state = '".$state."';";
mysqli_multi_query($con,$query);
or in MySQL WorkBench:
Edit -> Preferences -> SQL Queries
Uncheck Forbid UPDATE and DELETE statements without a WHERE clause
(safe updates)
Query --> Reconnect to Server
$query = 'SET SQL_SAFE_UPDATES=0;';
$query .= 'custom query here;';
$query .= 'SET SQL_SAFE_UPDATES=1;';