Tass Mark
Tass Mark

Reputation: 337

What is the proper way in PHP multiple post values as input for MySQL query?

I would like to make a code where it get data from POST, POST contains checkbox selections (multiple selections), and the feed these data into a MySQL SELECT.

My basic code is:

echo "<form action='handler.php' method='post'>";

echo '<input type="checkbox" name="cbtest" value="10">href="details.php?id=10">data 1</a>';

echo '<input type="checkbox" name="cbtest" value="11">href="details.php?id=11">data 2</a>';

echo '<input type="checkbox" name="cbtest" value="12">href="details.php?id=12">data 3</a>';

echo "<input type='submit' name='button' value='Some action'>";
echo '</form>';

Handler.php contains:

$temp = $_POST['cbtest'];

if(isset($_POST['cbtest'])) {
foreach ($temp as $cbtest){
echo $cbtest."<br>";
}

It is clear that $cbtest variable will contain the actual POSTed data for each round of foreach command running.

But how can I catch all the data from $cbtest and run a query with a statement like this:

$query = "SELECT data_id, data_content WHERE data_id = $cbtest";

I would like to display all data_content table data for each matching iD/value in the POST variable.

How is it needed to write correctly ?

Upvotes: 0

Views: 857

Answers (2)

Catharsis
Catharsis

Reputation: 657

Take a look into PDO or mysqli and the prepare & execute details in the docs, below is an example.

$insert = "INSERT INTO `table` (`field1`, `field2`), VALUES (?, ?)";

$stmt = mysqli_prepare($dbConnection, $insert);
$stmt->bind_param('ss', $field1, $field2);
$stmt->execute();

// Create a PDO object
$stmt = $pdoObj->prepare($insert);
$stmt->execute([$field1, $field2]);

Upvotes: 1

Ammadu
Ammadu

Reputation: 1675

If you want multiple values for checkbox selection then make the change as follow

<input type="checkbox" name="cbtest[]" value="10">href="details.php?id=10">data 1</a>

Now in the php $_POST['cbtest'] would return array of the checked inputs. Here is the php code you need to manipulate the query.

$checkedInputs = implode(',',$_POST['cbtest']);
$query = "SELECT data_id, data_content WHERE data_id IN (".$checkedInputs.")";

PS: Please escape your inputs and change the query into a prepeared statement.

Upvotes: 1

Related Questions