Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL Prepared statements select all result with =

So I’m using prepared statements in PHP to send a SQL command where there 5 different matching columns. The goal is that there should be an option where if only one column is selected the command should be able to run. And the options should also work if you choose all of the 5 different matching columns.

$sqlPrepared = $conn->prepare("SELECT * FROM crashes_history WHERE region = ? AND county = ? and crash_id = ?");
$sqlPrepared->bind_param("sssii", $region,  $county, $crash_id, $limit, $offset);

So what I did is that if the $region doesn’t exist we set the $region parameter to ‘region’ to select all results. But unfortunately, this doesn’t work with prepared statements.

An example where no columns are selected (fetch all data)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT * FROM crashes_history WHERE region = region AND county = county and crash_id = crash_id

>Solution :

You may use a flexible prepared statement here which will ignore a given column should it be NULL:

$sql = "SELECT *
        FROM crashes_history
        WHERE region = ? OR ? IS NULL AND
              county = ? OR ? IS NULL AND
              crash_id = ? OR ? IS NULL";
$sqlPrepared = $conn->prepare($sql);
$sqlPrepared->bind_param("ssssssii", $region, $region, $county, $county, $crash_id, $crash_id, $limit, $offset);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading