Created
December 19, 2019 19:11
-
-
Save thepsion5/1a3495e2f88b5286d5b247098bf9597b to your computer and use it in GitHub Desktop.
Example solution for a question posted in a PHP Facebook group
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
The question: | |
if ( $date_text == 'Sunday' ){ | |
$sql = "update table set sun = $date where "id ='$_REQUEST[num]"; | |
$sql1= "update table set sun = $date where "id ='$_REQUEST[num1]"; | |
mysql_query($con,$sql); | |
mysql_query($con,$sql1); | |
} | |
I have more than 7 SQL queries... $sql1, $sql2, etc | |
How can i make all these lines short and easy to read? | |
*/ | |
$pdo = new PDO('some valid DSN'); | |
$date_text = $_REQUEST['some-field']; | |
$date = $_REQUEST['some-other-field']; | |
//define the valid weekday columns associated with the date field | |
$dateColumns = [ | |
'Sunday' => 'sun', | |
'Monday' => 'mon', | |
'Tuesday' => 'tues', | |
'Wednesday' => 'wed', | |
'Thursday' => 'thurs', | |
'Friday' => 'fri', | |
'Saturday' => 'sat' | |
]; | |
if (!array_key_exists($date_text, $dateColumns)) { | |
//handle the error | |
} | |
//Retrieves all the IDs that are being updated | |
$queryParams = [$date]; | |
for($i = 1; $i < 10; $i++) { | |
$idKey = 'num' . $i; | |
if ($_REQUEST[$idKey]) { | |
$queryParams[] = $_REQUEST[$idKey]; | |
} | |
} | |
//Create the SQL "in" clause string using placeholders | |
$idClause = trim( str_repeat('?, ', count($ids)), ', '); | |
//Create and then execute the SQl query | |
$sqlClause = <<<SQL | |
UPDATE `table` SET {$dateColumns[$date_text]} = ? WHERE id IN($idClause) | |
SQL; | |
$query = $pdo->prepare($sqlClause); | |
$query->execute($queryParams); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment