Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Integrating PHP with Databases Using Relational Tables Preparing SQL Statements

Daniel Malek
Daniel Malek
20,140 Points

use string variable and placeholders with mysql

My function works but

function alphabetical_car_list ($subsection) { include("dbconnection.php"); try { $results = $db->prepare( ' select * from ram_cars WHERE car_reg LIKE "'.$subsection.'%" ); $results->bindParam(1,$subsection,PDO::PARAM_STR, 12); $results->execute(); } catch(Exception $e) { echo "error: " . $e->getMessage(); } $cars = $results-> fetchAll(PDO::FETCH_ASSOC); return $cars;

}

if I use placeholder like that

function alphabetical_car_list ($subsection) { include("dbconnection.php"); try { $results = $db->prepare( ' select * from ram_cars WHERE car_reg LIKE "?%" ' ); $results->bindParam(1,$subsection,PDO::PARAM_STR, 12); $results->execute(); } catch(Exception $e) { echo "error: " . $e->getMessage(); } $cars = $results-> fetchAll(PDO::FETCH_ASSOC); return $cars;

}

it returns an empty array. I tried many combinations of double and single quotation marks. But my mistake might be somewhere else.

Hey Daniel Malek, Try to write script using bindValue

  function alphabetical_car_list ($subsection) { 
include("dbconnection.php");
 try { 
 $results = $db->prepare( ' select * from ram_cars WHERE car_reg LIKE  ? ' ); 
 $results->bindValue(1,$subsection."%",PDO::PARAM_STR); 
 $results->execute();
  } catch(Exception $e) { 
  echo "error: " . $e->getMessage(); 
  } 
  $cars = $results-> fetchAll(PDO::FETCH_ASSOC);
   return $cars;

}

1 Answer

Daniel Malek
Daniel Malek
20,140 Points

works perfectly :) Thank You Ashish Mehra