Looking for a cleaner way to run a query that has to check for multiple "AND" conditions - mysql

I'm running a query against a database and have to check for multiple conditions to be true. The code I have pulls the data I want, but if I had to check many more columns, it could get out of control very quickly. I don't want a query that where I have to write out a dozen or so "AND" conditions. I'm learning some MySQL as I go and any help would be appreciated.
<?php
$servername = "localhost";
$username = "xxxx";
$password = "xxxx";
$dbname = "oldga740_SeniorProject";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Set up and run my Query
$sql = "SELECT Project, Client, DateReceived, LastName, FinalReviewDate FROM Projects
WHERE FinalReviewDate IS NOT NULL
AND DateDelivered IS NULL
AND DateAccepted IS NULL
ORDER BY DateAccepted DESC";
$result = $conn->query($sql);
//Display results
if ($result->num_rows > 0) {
echo "<table><tr><th>Client</th><th>Project</th><th>Point of Contact</th><th>Date Project Received</th><th>Final Review Date</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["Client"]. "</td><td>" . $row ["Project"]. "</td><td> " . $row["LastName"]. "</td><td> " . $row ["DateReceived"]. "</td><td> " . $row["FinalReviewDate"]. "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>

You can use an array for your and conditions. But in general you have to be careful if you are going to have prepared statements and bind values. Also, you can create your WHERE clause dynamically in a similar way like the following:
EDIT:
$where = array(
array(
'column'=>'FinalReviewDate',
'operator'=>'AND',
'condition'=>'IS NOT NULL',
'value'=>'',
),
array(
'column'=>'DateDelivered',
'operator'=>'AND',
'condition'=>'IS NULL',
'value'=>'',
),
array(
'column'=>'DateAccepted',
'operator'=>'AND',
'condition'=>'IS NULL',
'value'=>'',
),
array(
'column'=>'other_column',
'operator'=>'OR',
'condition'=>'>=',
'value'=>5,
),
);
$temp = array();
foreach($where as $key => $value) {
if ($value['value'] == '') {
$temp[] = $value['operator'].' '.$value['column'].' '.$value['condition'];
} else {
$temp[] = $value['operator'].' '.$value['column'].' '.$value['condition'].' '.$value['value'];
}
}
$where_sql = '1 = 1 '.implode(' ', $temp);
echo $where_sql;
Result:
1 = 1 AND FinalReviewDate IS NOT NULL AND DateDelivered IS NULL AND DateAccepted IS NULL OR other_column >= 5
OLD ANSWER
$ands = array(
array(
'column'=>'FinalReviewDate',
'condition'=>'IS NOT NULL'
),
array(
'column'=>'DateDelivered',
'condition'=>'IS NULL'
),
array(
'column'=>'DateAccepted',
'condition'=>'IS NULL'
),
);
$temp = array();
foreach($ands as $key => $value) {
$temp[] = $value['column'].' '.$value['condition'];
}
$and_sql = implode(' AND ', $temp);
echo $and_sql;
Result:
FinalReviewDate IS NOT NULL AND DateDelivered IS NULL AND DateAccepted IS NULL

Related

How to replace labels of json array and add information prior to the array

I'm fetching data from mysql like ...
$query = "SELECT legal_country, count(*) FROM accounts GROUP BY legal_country ORDER BY count(*) DESC";
$result = mysql_query( $query );
$data = array();
while ( $row = mysql_fetch_assoc( $result ) ) {
$data[] = $row;
}
return json_encode( $data );
Current result is:
[{"legal_country":"US","count(*)":"107865"},{"legal_country":"DE","count(*)":"44711"},{"legal_country":"SL","count(*)":"1"}]
Yet, my goal is to have the json string like:
{"map": "worldLow", "areas": [{"id": "US","value": "107865"},{"id": "DE","value": "44711"},{"id": "SL","value": "1"}]}
How can I add {"map": "worldLow", "areas": .... } prior to the array and how can I exchange the labels legal_country -> id and count(*) -> value ??
In addition, this is a working example with 'echo' ... yet I need it with the 'return' function ...
$prefix = '';
echo '{"map": "worldLow", "areas": [';
while ( $row = mysql_fetch_assoc( $result ) ) {
echo $prefix . " {\n";
echo ' "id": "' . $row['legal_country'] . '",' . "\n";
echo ' "value": "' . $row['count(*)'] . '"' . "\n";
echo " }";
$prefix = ",\n";
}
echo "\n]}";
The working example with echo looks like this:
{"map": "worldLow", "areas": [ {
"id": "US",
"value": "107865"
},
{
"id": "DE",
"value": "44711"
},
{
"id": "SL",
"value": "1"
}
]}
Create an array with the result according to your requirement.
$query = "SELECT legal_country AS `id`, count(*) AS `value`
FROM accounts
GROUP BY legal_country
ORDER BY count(*) DESC";
$dataArr = $areasArr = array();
if ($result = mysql_query( $query )) {
while ( $row = mysql_fetch_assoc( $result ) ) {
$areasArr[] = $row;
}
$dataArr = array(
"map" => "worldLow",
"areas" => $areasArr
);
}
return json_encode( $dataArr, true );
Also use mysqli_* functions instead of mysql_*
You have to change slightly your query and $data before using json_encode
$query = "SELECT legal_country as `id`, count(*) as `value` FROM accounts GROUP BY legal_country ORDER BY count(*) DESC";
$result = mysql_query( $query );
$json= array();
$area = array();
while ( $row = mysql_fetch_assoc( $result ) ) {
$area[] = $row;
}
$data = array(
'map' => 'worldlow',
'area' => $area,
);
return json_encode( $data );

Import CSV in Mysql does not work

I like to write a csv import / update to my Mysql database, but it isnt working. I get no error messages.
Can anybody help me to find the error or whats wrong with my script please.
// set local variables
$connect = mysql_connect("localhost","root","") or die('Could not connect: ' . mysql_error());
$handle = fopen("imptest.csv", "r");
// connect to mysql and select database or exit
mysql_select_db("shoptest1", $connect);
while($data = fgetcsv($handle, 30000, ';')) //Jede Zeile durchgehen
{
$Product_ID=$data[0];
$field=$data[1];
$query = 'SELECT Product_ID FROM testprod';
if (!$result = mysql_query($query)) {
continue;
} if ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
// entry exists update
$query = "UPDATE ps_product_lang SET custom_field ='$field' WHERE id_product = '$Product_ID'";
mysql_query($query);
if (mysql_affected_rows() <= 0) {
echo "kein update";
// no rows where affected by update query
}
} else {
echo "kein eintrag";
// entry doesn't exist continue or insert...
}
mysql_free_result($result);
}
fclose($handle);
mysql_close($connect);
?>
The queries you are performing:
SELECT Product_ID FROM testprod
UPDATE nl_product_lang SET custom_field = ? WHERE Product_ID = ?
are suitable to detect whether a product exists and then either UPDATE or INSERT. For only an UPDATE, the SELECT doesn't matter, as there won't be an entry WHERE Product_ID NOT IN (SELECT Product_ID FROM testprod) - if you have a foreign key.
Here's an example of how to do this using PDO.
list( $SQLDSN, $SQLUSER, $SQLPASS ) = [ 'mysql:dbname=shoptest1', 'root', '' ];
$db = new PDO( $SQLDSN, $SQLUSER, $SQLPASS, [
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
] );
$ids = $db->query( "SELECT Product_ID from testprod" )->fetchAll( \PDO::FETCH_COLUMN, 0 );
while ( list( $Product_ID, $field ) = fgetcsv(...) )
if ( in_array( $Product_ID, $ids ) )
query( $db, "UPDATE ps_product_lang SET custom_field = ? WHERE Product_ID = ?",
[ $field, $Product_ID ]
);
else
trigger_warning( "unknown product $Product_ID" );
function query( $db, $sql, $args = null ) {
$sth = $db->prepare( $sql );
$sth->execute( $sql );
return $sth;
}

Selecting Closest Values In MySQL

I'm referring to this tutorial: http://www.techfounder.net/2009/02/02/selecting-closest-values-in-mysql/
My query and code to execute search (This doesn't return any result).I need to get 100 closets value to the postcode given by user which is collected by $postcode = $data['postcode'];
ERROR shown is: Fatal error: Uncaught exception 'PDOException' with
message 'SQLSTATE[HY093]: Invalid parameter number: number of bound
variables does not match number of tokens' in
$return = $_POST;
//$return='{"sub":{"1":"","2":""},"postcode":"56000","slider1":"100","action":"test"}';
$return["json"] = json_encode($return);
// echo json_encode($return);
$data = json_decode($return["json"], true);
//var_dump($data);
include($_SERVER['DOCUMENT_ROOT']."/config.php");
$key =array_keys($data['sub']);
//print_r($key);
$pricing2 = $data['slider1'];
$pricing = $pricing2 * 1.15;
$postcode = $data['postcode'];
$bindings = array();
$bindings[] = array(":pricing", $pricing, PDO::PARAM_STR);
$bindings[] = array(":distance", $postcode, PDO::PARAM_STR);
$key_placeholders = array();
foreach($key as $k => $v) {
$placeholder = ":subid".$k;
$bindings[] = array($placeholder, $v, PDO::PARAM_INT);
$key_placeholders[] = $placeholder;
}
$sql = "SELECT Name,PostUUID,pricing,Poscode,subname,Reputation,ReviewPlus,ReviewNeg,week_morning,week_afternoon,week_evening,weekend_morning,week_afternoon,week_evening,weekend_morning,weekend_afternoon,week_evening,weekend_morning,weekend_afternoon,weekend_evening,date,Phone,Sex,UUID,catname FROM posts,subjects "
. "WHERE posts.subid IN (". implode(",",$key_placeholders).") "
. "AND posts.pricing <=:pricing "
. "AND posts.Poscode, ABS( posts.Poscode - :distance ) AS distance " distance "
. "AND posts.subid=subjects.subid "
. "ORDER BY distance "
. "DESC LIMIT 100";
$statement = $pdo->prepare($sql);
foreach($bindings as $b) {
$statement->bindValue($b[0],$b[1],$b[2]);
}
$statement->execute();
$json = array();
while( $row = $statement->fetch()) {
array_push($json, array("name" => $row['Name'], "id" => $row['PostUUID'],"rate" => $row['pricing'],"postcode" => $row['distance'],"subject" => $row['subname'],"reputation" => $row['Reputation'],"plus" => $row['ReviewPlus'],"neg" => $row['ReviewNeg'],"weekM" => $row['week_morning'],"weekA" => $row['week_afternoon'],"weekE" => $row['week_evening'],"endM" => $row['weekend_morning'],"endA" => $row['weekend_afternoon'],"endE" => $row['weekend_evening'],"postDate" => $row['date'],"contact" => $row['Phone'],"gender" => $row['Sex'],"tid" => $row['UUID'],"levelName" => $row['catname']));
}
header('Content-Type: application/json');
echo json_encode($json);
$sql = "SELECT Name,PostUUID,pricing,Poscode , ABS( Poscode - :distance ) AS distance,subname,Reputation,ReviewPlus,ReviewNeg,week_morning,week_afternoon,week_evening,weekend_morning,week_afternoon,week_evening,weekend_morning,weekend_afternoon,week_evening,weekend_morning,weekend_afternoon,weekend_evening,date,Phone,Sex,UUID FROM posts,subjects "
. "WHERE posts.subid IN (". implode(",",$key_placeholders).") "
. "AND posts.pricing <=:pricing "
. "AND posts.Poscode =:distance "
. "AND posts.subid=subjects.subid "
. "ORDER BY distance "
. "DESC LIMIT 100";

PDO Double LIKE with Params

I'm executing a query with PDO that doesn't retrieve any result via PHP but works in phpMyAdmin.
I'm sure about the connections setting as it's not the first query of my script and the other ones work fine.
Here the PHP code :
$retour = array();
$filters = array();
$filters['media_type'] = 'mytype';
$filters['libelle'] = 'sometext';
$start = 0;
$count = 9;
$sql = "SELECT * FROM ".DB_PROD_PREFIX.$this->table." t ";
$sql .= " LEFT JOIN ".DB_PROD_PREFIX.$this->table."_lang l ON t.id = l.id AND l.langue = :langue";
$sql .= " WHERE 1";
if (count($filter)>0){
foreach($filter as $field => $value){
$sql .= " AND ".$field." LIKE :".$field;
}
}
$sql .= ($order!='' ? " ORDER BY ".$order : '');
$sql .= ($count != '' ? " LIMIT ".($start != ''?':start':'0').", :count" : '');
$stmt = $db->prepare($sql);
if($start != '') $stmt->bindParam('start', $start, PDO::PARAM_INT);
if($count != '') $stmt->bindParam('count', $count, PDO::PARAM_INT);
if ($langue != '') $stmt->bindParam('langue', $langue);
if (count($filter)>0){
foreach($filter as $field => $value) {
$f = '%'.$value.'%';
$stmt->bindParam($field, $f, PDO::PARAM_STR);
}
}
echo $stmt->queryString.print_r($filter, true);
if (!$stmt->execute()) echo $stmt->errorInfo();
$res = $stmt->fetchAll();
foreach($res as $id => $row){
$retour[]=$row;
}
return $retour;
If I unset one of the 2 keys of $filter array, the query work fine.
Here is the SQL generated :
SELECT * FROM table1 t
LEFT JOIN table1_lang l ON t.id = l.id AND l.langue = :langue
WHERE 1
AND media_type LIKE :media_type
AND libelle LIKE :libelle
ORDER BY position LIMIT :start, :count
Thanks for your help!
Pierre M.
It doesn't work better but thanks for the tip!
Here is a piece of code managing the LIKE parameters that works :
$media_type = '%'.$filter['media_type'].'%';
$stmt->bindParam('media_type', $media_type, PDO::PARAM_STR);
$libelle = '%'.$filter['libelle'].'%';
$stmt->bindParam('libelle', $libelle, PDO::PARAM_STR);
Why doing the same with a foreach on the array doesn't work ?
if (count($filter)>0){
foreach($filter as $field => $value) {
$value = "%$value%";
$stmt->bindParam($field, $value, PDO::PARAM_STR);
}
}

Simulate a DELETE CASCADE in MySQL?

Is it possible to predict the operations that follow a DELETE CASCADE automatically? In my software I would like to give the user a warning with details about the data that would be deleted then.
You can make a copy of the database and put triggers on the after delete
DELIMITER $$
CREATE TRIGGER ad_table1_each AFTER DELETE ON table1 FOR EACH ROW
BEGIN
INSERT INTO log VALUES (null /*autoinc id*/
, 'table1' /*tablename*/
, old.id /*tableid*/
, concat_ws(',',old.field1,old.field2 /*CSV's of fields*/
, NOW() /*timestamp*/
, 'delete'); /*what action*/
REPLACE INTO restore_table1 VALUES (old.id,
, old.field1
, old.field2
, ... );
END $$
DELIMITER ;
The log table is just a table with the following fields:
id integer autoincrement primary key
tablename varchar(45)
table_id integer
fields varchar(6000)
delete_time timestamp
action enum('insert','update','delete')
If you do a SELECT #last_id:= max(id) FROM log before the delete cascade on the copy.
Then you can do a SELECT * FROM log WHERE id > #last_id
and get all the rows that will be deleted in the cascade.
After that you can use the restore_table1 to recreate the rows that were deleted in the cascade in the copy database.
I think you could use Johan's trigger solution in combination with a transaction that you roll back. This avoids both the need for a second database and for the manual restore of the deleted entries.
add the trigger and the log table
for each attempted deletion start a transaction and delete the entries
present the information from the log to your user for approval
if the user agrees commit the transaction, otherwise rollback
I wrote a very quick hack that does exactly what you need in PHP, since I wanted to do the exact same thing and haven't found any resources for that online.
It might be too late for you, but it may help others.
function get_referencing_foreign_keys ($database, $table) {
$query = 'SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = "'.$database.'" AND REFERENCED_TABLE_NAME = '.esc($table);
$result = rquery($query);
$foreign_keys = array();
while ($row = mysql_fetch_row($result)) {
$foreign_keys[] = array('database' => $row[0], 'table' => $row[1], 'column' => $row[2], 'reference_column' => $row[3]);
}
return $foreign_keys;
}
function get_foreign_key_deleted_data_html ($database, $table, $where) {
$data = get_foreign_key_deleted_data ($database, $table, $where);
$html = '';
foreach ($data as $key => $this_data) {
$html .= "<h2>$key</h2>\n";
$html .= "<table>\n";
$i = 0;
foreach ($this_data as $value) {
if($i == 0) {
$html .= "\t<tr>\n";
foreach ($value as $column => $column_value) {
$html .= "\t\t<th>".htmlentities($column)."</th>\n";
}
$html .= "\t</tr>\n";
}
$html .= "\t<tr>\n";
foreach ($value as $column => $column_value) {
$html .= "\t\t<td>".htmlentities($column_value)."</td>\n";
}
$html .= "\t</tr>\n";
$i++;
}
$html .= "</table>\n";
}
return $html;
}
function get_foreign_key_deleted_data ($database, $table, $where) {
$GLOBALS['get_data_that_would_be_deleted'] = array();
$data = get_data_that_would_be_deleted($database, $table, $where);
$GLOBALS['get_data_that_would_be_deleted'] = array();
return $data;
}
function get_data_that_would_be_deleted ($database, $table, $where, $recursion = 100) {
if($recursion <= 0) {
die("Deep recursion!");
}
if($recursion == 100) {
$GLOBALS['get_data_that_would_be_deleted'] = array();
}
if($table) {
if(is_array($where)) {
$foreign_keys = get_referencing_foreign_keys($database, $table);
$data = array();
$query = 'SELECT * FROM `'.$table.'`';
if(count($where)) {
$query .= ' WHERE 1';
foreach ($where as $name => $value) {
$query .= " AND `$name` = ".esc($value);
}
}
$result = rquery($query);
$to_check = array();
while ($row = mysql_fetch_row($result)) {
$new_row = array();
$i = 0;
foreach ($row as $this_row) {
$field_info = mysql_fetch_field($result, $i);
$new_row[$field_info->name] = $this_row;
foreach ($foreign_keys as $this_foreign_key) {
if($this_foreign_key['reference_column'] == $field_info->name) {
$to_check[] = array('value' => $this_row, 'foreign_key' => array('table' => $this_foreign_key['table'], 'column' => $this_foreign_key['column'], 'database' => $this_foreign_key['database']));
}
}
$i++;
}
$GLOBALS['get_data_that_would_be_deleted'][$table][] = $new_row;
}
foreach ($to_check as $this_to_check) {
if(isset($this_to_check['value']) && !is_null($this_to_check['value'])) {
get_data_that_would_be_deleted($database, $this_to_check['foreign_key']['table'], array($this_to_check['foreign_key']['column'] => $this_to_check['value']), $recursion - 1);;
}
}
$data = $GLOBALS['get_data_that_would_be_deleted'];
return $data;
} else {
die("\$where needs to be an array with column_name => value pairs");
}
} else {
die("\$table was not defined!");
}
}
Imagine I have a table called "table" in the database "db" and I want to delete the one with the id 180, then I'd call:
print(get_foreign_key_deleted_data_html('db', 'table', array('id' => 180)));
and it prints a full table with all the rows and all the values that would be deleted.
But as I've said, this is a very, very quick and dirty hack. I'd be glad for any bug-report (and there surely are a lot of them!).