i'm moving of lamp websites
mysql_
functions pdo
functions , i've hit first brick wall. don't know how loop through results parameter. fine following:
foreach ($database->query("select * widgets") $results) { echo $results["widget_name"]; }
however if want this:
foreach ($database->query("select * widgets something='something else'") $results) { echo $results["widget_name"]; }
obviously 'something else' dynamic.
here example using pdo connect db, tell throw exceptions instead of php errors (will debugging), , using parameterised statements instead of substituting dynamic values query (highly recommended):
// $attrs optional, demonstrates using persistent connections, // equivalent of mysql_pconnect $attrs = array(pdo::attr_persistent => true); // connect pdo $pdo = new pdo("mysql:host=localhost;dbname=test", "user", "password", $attrs); // following tells pdo want throw exceptions every error. // far more useful default mode of throwing php errors $pdo->setattribute(pdo::attr_errmode, pdo::errmode_exception); // prepare statement. place holders allow pdo handle substituting // values, prevents sql injection $stmt = $pdo->prepare("select * product producttypeid=:producttypeid , brand=:brand"); // bind parameters $stmt->bindvalue(":producttypeid", 6); $stmt->bindvalue(":brand", "slurm"); // initialise array results $products = array(); if ($stmt->execute()) { while ($row = $stmt->fetch(pdo::fetch_assoc)) { $products[] = $row; } } // set pdo null in order close connection $pdo = null;
Comments
Post a Comment