Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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