PHP Operations Database
Load Database Driver
Visit phpinfo.php to see if the database driver has been loaded, for example, the following display has not been loaded into MySQL database driver.
Locate the php.ini configuration file on the C drive to load the MySQL driver, for example, to remove the semicolon.
Connecting to a database
<?php
connecting to a database
$DSN = "mysql:dbname=test;host=127.0.0.1";// Data Source name
$user = "root";//username
$password = "715632";// Password
try{
$pdoConn =new PDO ($dsn, $user, $password);
echo " database connection succeeded ";
}catch (Pdoexception $e) {
echo " database connection failed ". $e->getmessage ();
Exit
}
manipulating databases
<?php
connecting to a database
$DSN = "mysql:dbname=test;host=127.0.0.1";// Data Source name
$user = "root";//username
$password = "715632";// Password
try{
$pdoConn =new PDO ($dsn, $user, $password);
echo " database connection succeeded ". " <br/> ";
}catch (Pdoexception $e) {
echo " database connection failed ". $e->getmessage ();
Exit
}
try{
Insert Operation
/* $sql = "INSERT into Contacts (Name,telno,email) VALUES (?,?,?)";
$ptmt = $pdoConn->prepare ($sql);
$name = "Liujun";
$telno = "347535420";
$email = "[email protected]";
$ptmt->bindparam (1, $name);
$ptmt->bindparam (2, $telno);
$ptmt->bindparam (3, $email);
$result = $ptmt->execute ();
echo " affects line count:". $result;
*/
Query Operations
$sql = "SELECT * from Contacts";
$ptmt = $pdoConn->prepare ($sql);
$result = $ptmt->execute ();
if ($result ==1) {// contains result set
while ($list = $ptmt->fetch ()) {
echo $list [' name ']. " -----". $list [' Telno ']." ----". $list [' email ']." <br/> ";
}
}
}catch (Pdoexcepton $e) {
echo " database operation failed ";
Exit
}
Instance code:xsphp/demo.php
PHP Operating Database PDO