I want to use PDO and bind an array of data from a select list, and a text field to a MYSQL query. That means I want to bind an array and a value. Now I know you can bind an array to the execute() method, however what about the value? Can I add the value and array to another array and execute() it? How would I do that? Here is an example of what I am trying to do:
Jobsearch Web page example:
<html>
<head>
<?php
require_once("include/config.php");
session_start();
?>
</head>
<body>
<h1>Jobsearch</h1>
<form method="post" action="">
<h2>Keyword</h2>
<input type="text" placeholder="Keyword" name="keyword">
<h2>Location</h2>
<select name="location[]" id="location" title="location" multiple>
<option value="Central Coast">Central Coast</option>
<option value="Hunter Valley">Hunter Valley</option>
<option value="Illawarra">Illawarra</option>
<option value="Richmond">Richmond</option>
<option value="Ballarat">Ballarat</option>
<option value="Riverina">Riverina</option>
<option value="Murray">Murray</option>
<option value="Mid North Coast">Mid North Coast</option>
</select>
<h2>Occupation</h2>
<select name="occupation[]" id="occupation" title="occupation" multiple>
<option value="Accounting">Accounting</option>
<option value="Education">Education</option>
<option value="Healthcare">Healthcare</option>
<option value="Information Technology">Information Technology</option>
<option value="Retail">Retail</option>
<option value="Sales">Sales</option>
</select>
<br/><br/>
<button type="submit" name="search_jobs" >Search Jobs</button>
<?php
if(isset($_POST['search_jobs']))
{
//create query
$sql = "SELECT * FROM job, location, occupaton WHERE job.title LIKE CONCAT('%', ?, '%') ";
$keyword = $_POST['keyword']; //value
$occupation = $_POST['occupation']; //array
$location = $_POST['location']; //array
if($keyword == NULL)
{
$keyword = " ";
}
if($occupation != NULL)
{
$occs = implode(',', array_fill(0, count($occupation), '?'));
$sql = $sql . "AND occupation.name IN ($occs) ";
}
if($location !=NULL)
{
$locs = implode(',', array_fill(0, count($location), '?'));
$sql = $sql . "AND location.region IN ($locs) ";
}
$sql = $sql . "AND job.location_id = location.id
AND job.occupation_id = occupation.id";
echo "<br/><br/><b>" . $sql . "</b><br/>";
//get results
try
{
$stmt = $DB->prepare($sql);
//$stmt->execute([$keyword, $occupation, $location]);
//$data = array_merge($keyword, $occupation, $location);
//$stmt->execute($data); //what do i do here?
$results = $stmt->fetchAll();
}
catch (Exception $ex)
{
echo $ex->getMessage();
}
//print results
echo "<h2>Results</h2>";
foreach($results as $res)
{
echo "<p>Title:" . $res['title'];
echo "<p>Views:" . $res['views'];
echo "<p>Created At:" . $res['created_at'];
echo "<p>Image:" . $res['img_url'];
echo "<p>Salary:" . $res['salary'];
echo "<p>Region:" . $res['region'];
echo "<p>Region:" . $res['location_id'];
echo "<p>State:" . $res['state'];
echo "<br/><br/>";
}
}
?>
</form>
</body>
</html>