PHP Operations Database
Load Database Driver
Access phpinfo.php can see if the database driver has been loaded and the MySQL database driver has not been loaded as shown below.
Locate the php.ini config file on the C drive to load the MySQL driver, for example, 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