PDO with MySQL; PHP v. 5.2.14
I have a search form with a text box for user input and radio buttons to choose to search either by author or title. The ouput will eventually be paginated.
I am new to PDO and am still absorbing the basics. So I would appreciate knowing if I am on the right track. I had gotten the basic SQL down so things work but now I want to put a variable as the column. I have learned that PDO does not accept table or column names as parameters. So I have tried the following:
EDITED with Corrections AND Added Variation on Binding Parameters
try {
if (isset($_POST['submit1'])) {
echo '<pre>', print_r ($_POST, TRUE), '</pre>';
$selected_radio = $_POST['text_search'];
if ($selected_radio == 'author') {
$_SESSION['where_field'] = 'author';
}
else if ($selected_radio == 'title') {
$_SESSION['where_field'] = 'title';
}
}
if (!empty($_POST['search_term'])){
$_SESSION['search_term'] = filter_var($_POST['search_term'], FILTER_SANITIZE_STRING);
}else {
echo "please enter a search term.";
}
echo "search term: " . $_SESSION['search_term'] . "<br />";
// Find out how many items are in the table
$sql = "SELECT COUNT(*) as num_books from t_books where ".
$_SESSION['where_field'] ." LIKE :search_term';
$prep = $dbh->prepare($sql);
$num = $prep->execute(array(':search_term' => '%'.$_SESSION['search_term']. '%'));
var_dump($prep);
echo "<br />";
if ($num) {
$total = $prep->fetchColumn();
}
echo "total: $total <br />";
VARIATION:
$sql = "SELECT COUNT(*) as num_books from t_books where ". $_SESSION['where_field'] . " LIKE
CONCAT('%',:search_term,'%')";
$prep = $dbh->prepare($sql);
$prep->bindParam(':search_term', $_SESSION['search_term'], PDO:: PARAM_STR);
$prep->execute();
if ($prep) {
$total = $prep->fetchColumn();
}
STRING QUOTE PROBLEM: My initial attempts and the errors
$sql = 'SELECT COUNT(*) as num_books from t_books where '". $_SESSION['where_field'] ."'
LIKE :search_term';
Parse Error
$sql = "SELECT COUNT(*) as num_books from t_books where $_SESSION['where_field']
LIKE :search_term";
Parse error: parse error, expecting `T_STRING' or `T_VARIABLE' or `T_NUM_STRING'
$sql = "SELECT COUNT(*) as num_books from t_books where ". $_SESSION['where_field'] . "
LIKE :search_term";
Notice: Undefined index: where_field
Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to use near 'LIKE '%the%''
at line 1
$sql = 'SELECT COUNT(*) as num_books from t_books where ' . "$where_field" . 'LIKE :search_term';
Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to use near 'LIKE '%the%'' at
line 1
I am finding it hard to follow what is going on with the quotes. Thank you for any course correction and insights you may give.
Try this.