I'm using the following code to select data from a MySQL table. Can someone tell me how to improve this as it seems a bit messy?
Also, I need to run an UPDATE statement to increment the value in the "views" column each time a customer is queried from the database. Each customer row in the database has a column named "views". For example, say ABC Corp has 100 views. If I search for ABC Corp and the database returns the record, the "views" column for this record should be updated to 101. What is the best way to do this?
if ($search && ($group && $group !== "*")) {
$sql = "SELECT * FROM customers WHERE description LIKE :description AND groupId LIKE :groupId";
$result = $conn->prepare($sql);
$result->bindValue(":description", "%" . $search . "%", PDO::PARAM_STR);
$result->bindValue(":groupId", $groupId, PDO::PARAM_INT);
} else if ($search) {
$sql = "SELECT * FROM customers WHERE description LIKE :description";
$result = $conn->prepare($sql);
$result->bindValue(":description", "%" . $search . "%", PDO::PARAM_STR);
} else if ($group !== "*") {
$sql = "SELECT * FROM customers WHERE groupId LIKE :groupId";
$result = $conn->prepare($sql);
$result->bindValue(":groupId", $groupId, PDO::PARAM_INT);
} else {
$sql = "SELECT * FROM customers";
$result = $conn->prepare($sql);
}
How about something like this,
$sql = "SELECT * FROM customers ";
$and = $grp = FALSE;
if($search || ($group && $group !== "*") {
$sql .= " WHERE ";
if ($search) {
$sql .= " description LIKE :description ";
$and = TRUE;
}
if ($group && $group !== "*") {
if( $and === TRUE )
$sql .= " AND ";
$sql .= " groupId LIKE :groupId ";
$grp = TRUE;
}
}
$result = $conn->prepare($sql);
if( $and === TRUE)
$result->bindValue(":description", "%" . $search . "%", PDO::PARAM_STR);
if( $grp === TRUE)
$result->bindValue(":groupId", $groupId, PDO::PARAM_INT);
For the UPDATE statement,
//say $cust_name is the requested customer to be searched
$sql = "SELECT views from customers where customer_name = '" $cust_name."'";
$res = $conn->query($sql);
$views = $res->fetchColumn() + 1;
//sets 'views' to num_of_customers/rows returned.
$sql = "UPDATE customers SET VIEWS = " .$views." WHERE customer_name = '" $cust_name."'";
$res = $conn->query($sql);
Related
I've got below snippet where $filter_xx values are extracted from a dropdown basis user choice.
I'm trying to query the mySQL database with what the user chose to query the database with via dropdown selection.
You will see that there are 4 $filter_xx variables and how many of them are set in a given instance is completely random.
The issue is when I use && in the query it checks if all four parameters are true and then throws and output. (Well I know && is suppose to work that way!). I tried replacing all && operators with || and had no luck.
How do I search the database with only options selected by the user?
if(isset($filter_brand) || isset($filter_year) || isset($filter_month) || isset($filter_status))
{
$query = "SELECT * FROM targets WHERE brand='$filter_brand' && startyear='$filter_year' && startmonth='$filter_month' && status='$filter_status' ORDER BY createdon DESC";
} else {
$query = "SELECT * FROM targets ORDER BY createdon DESC";
}
When you have several values that must work in a similar manner, use an array together with loop. I am supposing, you are using mysqli, change quoting for PDO if needed.
$mysqli = new mysqli("localhost", "user", "pass", "test");
//...
//SQL attr name => name of POST parameter
$filter = array('brand' => 'brand', 'startyear' => 'year',
'startmonth' => 'month', 'status' => 'status');
//here we'll store SQL conditions
$sql_filter = array();
foreach($filter as $key => $value)
{
if (isset($_POST[$value]))
{
//use your library function to quote the variable before using it in SQL
$sql_filter[] = $key . '="'. $mysqli->escape_string($_POST[$value]) . '"';
}
}
$query = "SELECT * FROM targets ";
if(isset($sql_filter[0]))
{
$query .= 'WHERE ' . implode(' AND ', $sql_filter) . ' ';
}
$query .= 'ORDER BY createdon DESC';
Try By This
$join = "";
//TAKE ONE BLANK VARIBLE THAT JOIN IF VALUE IS SET
if(isset($filter_brand)){
//IF VALUE ISSET THAN IT ADDED TO QUERY
$join .= " AND brand='$filter_brand'";
}
if(isset($filter_year){
$join .= " AND startyear='$filter_year'";
}
$query = "SELECT * FROM targets WHERE id != '' $join ORDER BY createdon DESC";
You can do something like this:
$query = 'SELECT * FROM targets';
$flag = 0;
if(isset($filter_brand) )
{
$query = "SELECT * FROM targets WHERE brand='$filter_brand'";
$flag = 1;
}
if(isset($filter_year)) {
if($flag==1)
$query .= " &&";
$query .= " startyear='$filter_year'";
$flag = 1;
}
if(isset($filter_month)) {
if($flag==1)
$query .= " &&";
$query = " startmonth='$filter_month'";
$flag = 1;
}
if(isset($filter_status)){
if($flag==1)
$query .= " &&";
$query = " status='$filter_status'";
$flag = 1;
}
if($flag == 1){
$query .= " ORDER BY createdon DESC";
} else {
$query = "SELECT * FROM targets ORDER BY createdon DESC";
}
Try this:
$query = "SELECT * FROM targets WHERE 1 ";
$query = isset($filter_brand) ? $query . " AND brand = '".$filter_brand."'" : $query;
$query = isset($filter_year) ? $query . " AND startyear = '".$filter_year."'" : $query;
$query = isset($filter_month) ? $query . " AND startmonth = '".$filter_month."'" : $query;
$query = isset($filter_status) ? $query . " AND status = '".$filter_status."'" : $query;
$query .= " ORDER BY createdon DESC";
I have a if - else if statement changing the query from a db based on user input, and I'm displaying the respective results in while loop one for all the if - else if statements however how can I put the while loop into a variable such as $output then just echo that when the if conditions are met?
<?php include 'db_connect.php';
$job_title = $_POST['job_title'];
$company_name = $_POST['company_name'];
$salary = $_POST['salary'];
if($job_title !== " "){
$sql = $dbh->prepare("SELECT * FROM jobs_list WHERE jobTitle LIKE :job_title");
$sql->bindValue(':job_title', '%' . $job_title . '%', PDO::PARAM_INT);
if($sql->execute()) {
$sql->setFetchMode(PDO::FETCH_ASSOC);
}
// while loop here //
} else if($company_name !== " ") {
$sql = $dbh->prepare("SELECT * FROM jobs_list WHERE company_name LIKE :company_name");
$sql->bindValue(':company_name', '%' . $company_name . '%', PDO::PARAM_INT);
if($sql->execute()) {
$sql->setFetchMode(PDO::FETCH_ASSOC);
}
// while loop here //
}else if($salary !== " ") {
$sql = $dbh->prepare("SELECT * FROM jobs_list WHERE salary_info LIKE :salary");
$sql->bindValue(':salary', '%' . $salary . '%', PDO::PARAM_INT);
if($sql->execute()) {
$sql->setFetchMode(PDO::FETCH_ASSOC);
}
// while loop here //
} ?>
You can save the entire query result in a variable using PDOStatement::fetchAll. Later you use the query result outside of if-else block as per your requirement.
<?php
include 'db_connect.php';
$job_title = $_POST['job_title'];
$company_name = $_POST['company_name'];
$salary = $_POST['salary'];
$output = "";
if($job_title !== " "){
$sql = $dbh->prepare("SELECT * FROM jobs_list WHERE jobTitle LIKE :job_title");
$sql->bindValue(':job_title', '%' . $job_title . '%', PDO::PARAM_STR);
if($sql->execute()){
$output = $sql->fetchAll();
}
} else if($company_name !== " ") {
$sql = $dbh->prepare("SELECT * FROM jobs_list WHERE company_name LIKE :company_name");
$sql->bindValue(':company_name', '%' . $company_name . '%', PDO::PARAM_STR);
if($sql->execute()) {
$output = $sql->fetchAll();
}
}else if($salary !== " ") {
$sql = $dbh->prepare("SELECT * FROM jobs_list WHERE salary_info LIKE :salary");
$sql->bindValue(':salary', '%' . $salary . '%', PDO::PARAM_INT);
if($sql->execute()) {
$output = $sql->fetchAll();
}
}
// Now you can use that query result `$output` as per your requirement.
?>
Also, I changed the datatypes in ->bindValue() methods, and that's because I'm assuming jobTitle and company_name are of string datatype whereas salary is of integer type. If that's not the case then you need to change the datatypes in ->bindValue() methods accordingly.
Here's the reference:
http://php.net/manual/en/pdo.constants.php
Sidenote: If you want to see the entire query result structure, do var_dump($output);
You can just use the while loop just once after all the if-else statement has ended.
I have this query that shows some buildings that are for sale and where the user can select "plaats" (region) and slaapkamers (number of bedrooms). These are stored in variables and this query works:
$p = $_POST['plaats'];
$s = $_POST['slaapkamers'];
$sSql = "select * from tblpand WHERE PandPostcodeGemeente='". mysql_real_escape_string( $p ) ."' AND PandSlaapkamers='". mysql_real_escape_string( $s ) ."';
This works as long as long as the variable equals a field. For example, if $s equals 3, all buildings with 3 bedrooms are shown. However, there is also an option to select all number of bedrooms ("all"), same with regions, $p is "all" if all regions should be selected. I don't know how to add this to the query. Maybe something like:
$sSql = "select * from tblpand WHERE"If ($p != "all"){ PandPostcodeGemeente='". mysql_real_escape_string( $p ) ."'}" AND "If ($s != "all"){PandSlaapkamers='". mysql_real_escape_string( $s ) ."'}";
This is just a theoretical example, I know this won't work. Any ideas about this? Thank you all.
Try this:
$p = $_POST['plaats'];
$s = $_POST['slaapkamers'];
$sSql = "select * from tblpand WHERE 1=1";
if ($p !== 'all') {
$sSql .= " AND PandPostcodeGemeente='" . mysql_real_escape_string($p) . "'";
}
if ($s !== 'all') {
$sSql .= "AND PandSlaapkamers='" . mysql_real_escape_string($s) . "'";
}
Allow me to recommend a different approach, use this:
$p = filter_input(INPUT_POST, 'plaats', FILTER_SANITIZE_STRING);
$s = filter_input(INPUT_POST, 'slaapkamers', FILTER_SANITIZE_STRING);
$query = 'select * from tblpand ';
if (strcasecmp($p, 'all') !== 0) {
$query .= " WHERE PandPostcodeGemeente='". $p . "'";
$wherehasBeenSet = true;
}
if (strcasecmp($s, 'all') !== 0) {
if (isset($wherehasBeenSet)}) {
$query .= ' AND ';
} else {
$query .= ' WHERE ';
}
$query .= " PandSlaapkamers='" . $s . "'";
}
I am creating search query in php by passing variable through GET method. When the variable is null then it's passing the query like,
SELECT * FROM table WHERE column_name = null.
And it's showing error (obvious). I want to create query like. If user don't select anything from search options then it should fetch all the data from that column.
What's the correct logic for that?
Thanks.
Code:
if(isset($_GET['selPetType']) && $_GET['selPetType'] != '')
{
$searchParams['petType'] = $_GET['selPetType'];
$queryStr .= " PetType='" .$_GET['selPetType']. "'";
}
if(isset($_GET['txtPetBreed1']) && !empty($_GET['txtPetBreed1']))
{
$searchParams['breed'] = $_GET['txtPetBreed1'];
$queryStr .= " AND PetBreed1 ='". $_GET['txtPetBreed1'] . "'";
}
$clause1 = "SELECT * FROM pet WHERE $queryStr ORDER BY `Avatar` ASC LIMIT $startLimit, $pageLimit";
$totalRun1 = $allQuery->run($clause1);
Maybe something like this:
$get['param1'] = 'foo';
$get['param3'] = null;
$get['param2'] = '';
$get['param4'] = 'bar';
$where = null;
foreach ($get as $col => $val) {
if (!empty($val)) {
$where[] = $col . ' = "' . $val . '"';
}
}
$select = 'SELECT * FROM pet ';
if ($where) {
$select .= 'WHERE ' . implode(' AND ', $where);
}
$select .= ' ORDER BY `Avatar` ASC LIMIT $startLimit, $pageLimit';
Edit: I added if to remove empty values and added 2 new values to example so you can see this values will not be in query.
if(isset($_GET['your_variable'])){
$whr = "column_name = $_GET['your_variable']";
}
else{
$whr = "1 = 1";
}
$qry ="SELECT * FROM table WHERE ".$whr;
For example :
<?php
$userSelectedValue = ...;
$whereCondition = $userSelectedValue ? " AND column_name = " . $userSelectedValue : "" ;
$query = "SELECT * FROM table WHERE 1" . $whereCondition;
?>
Then consider it's more safe to use prepared statements.
I want to create sql queries dynamically depending upon the data I receive from the user.
Code:
$test = $_POST['clientData']; //It can be an array of values
count($test); //This can be 2 or 3 or any number depending upon the user input at the client
$query = "select * from testTable where testData = ".$test[0]." and testData = ".$test[1]." and . . .[This would vary depending upon the user input]"
Is it possible to achieve the above scenario. I am relatively new in this area.Your guidance would be helpful.
Use:
<?php
$test=$_POST['clientData'];//It can be an array of values
$query = "select *from testtable where 1 ";
foreach($test as $value) {
$query .= " AND testData='" . $value . "'";
}
echo $query;
?>
Use prepared statements:
$query = $dbh->prepare("SELECT * FROM testtable WHERE testData=:test0 and testData=:test1");
$query ->bindParam(':test0', $test0);
$query ->bindParam(':test1', $test0);
$test0 = $test[0];
$test1 = $test[1];
$query->execute();
Rishi that's a very long chapter.
If you want to search into a single field then you can try to do:
<?php
$test = $_POST[ 'clientData' ];
if( is_array( $test ) ){
$select = implode( ",", $test );
} else {
$select = $test;
}
$query=select *from testtable where testData IN ( $select );
?>
This is valid only for searches into a specific field.
If you want to create searches on multiple fields then you need to do a lot of more work, having an associative mapping which can create a relation variable name -> field_to_search
$data = $_POST['data'];
$query = "SELECT";
if ( is_set($data['columns']) )
$query .= " ".implode(',',$data['columns']);
else
$query .= "*";
if ( is_set($data['table']) )
$query .= " ".$data['table'];
and ...
This is very much pseudo code as I don't really know PHP, but could you not do something like this
$query = "select * from testable";
$count = count($test);
if($count > 0)
{
$query .= " where ";
for ($x=0; $x<=$count; $x++)
{
if($x > 0)
{
$query .= " and ";
}
$query .= " testData='" . $test[x] . "'";
}
}
$test=$_POST['clientData'];
$query="select * from testtable where testData='".$test[0]."' and testData='".$test[1]."' and . . .[This would vary depending upon the user input]";
$result = mysql_query($query);
$test=$_POST['clientData'];//It can be an array of values
$dValuesCount = count($test);//This can be 2 or 3 or any number depending upon the user input at the client
$query="select *from testtable ";
if ($dValuesCount > 0 ){
$query .= " WHERE ";
for ($dCounter = 0; $dCounter <= $dValuesCount ; $dCounter++){
$query .= "testData=" . $test[$dCounter];
if ($dCounter != ($dValuesCount - 1)){
$query .= " AND ";
}
}
}
$q="select *from table where ";
$a=count($test)-1;
$b=0;
while($element = current($test)) {
$key=key($array);
if($b!=$a){
$q.=$key."=".$test[$key]." and ";
}
else {
$q.=$key."=".$test[$key];
}
next($array);
$b=$b+1;
}
for this your array must contain columnname as key
for example
$test['name'],$test['lastname']
then it will return
$q="select * from table where name=testnamevalue and lastname=testlastnamevalue";
hope it works