mysql到pdo代码段

hof1towb  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(276)

很难找到有关如何将此mysql行重写为pdo的信息:

if ($_GET["action"] == "list")

在我试图转换的代码中,四个if/else语句类似于:

if ($_GET["action"] == "create") {
        //Insert record into database
        $result = mysql_query("INSERT INTO people(Name, Age, RecordDate) VALUES('" . $_POST["Name"] . "', " . $_POST["Age"] . ",now());");

        //Get last inserted record (to return to jTable)
        $result = mysql_query("SELECT * FROM people WHERE PersonId = LAST_INSERT_ID();");
        $row = mysql_fetch_array($result);

        //Return result to jTable
        $jTableResult = array();
        $jTableResult['Result'] = "OK";
        $jTableResult['Record'] = $row;
        print json_encode($jTableResult);
    }
bqf10yzr

bqf10yzr1#

我为您当前的场景提供了完整的pdo代码,该场景将数据插入表中,然后获取最后插入的记录的信息。为了更好地理解,您应该研究phppdo类。这真的很简单,很容易,你可以在这个主题上找到很多东西。

<?php

    //Specifying database credentials

    $dbhost = "localhost";// Your host name
    $dbname = "test"; // Your database name
    $dbuser = "root"; // database user
    $dbpass = "";// Database password

    $Name = $_POST["Name"];
    $Age = $_POST["Age"];
    $RecordDate = date("d-M-Y h:i:s a");
    $jTableResult = array();

    //Establishing connection to the database
    try
    {

        $db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);

    } catch (PDOException $e) {
        print "Error!: " . $e->getMessage();
        die();
    }

$sql = "INSERT INTO people(Name, Age, RecordDate) VALUES (:Name, :Age, :RecordDate)"; 
$statement = $db->prepare($sql);
//Bindging values to be added to People table
$statement->bindParam(":name", $firstname ); 
$statement->bindParam(":Age", $Age ); 
$statement->bindParam(":RecordDate", $RecordDate ); 

if($statement->execute()) // Check if insert statement executed successfully 
{

    $PersonId = $db->lastInsertId(); // Getting Last inserted id;

    $get_statement= $db->prepare("SELECT * FROM people WHERE PersonId=:PersonId");
    $get_statement->bindParam(":PersonId", $PersonId ); 

    $get_statement->execute(array(':Uemail'=>$email, ':Upassword'=>$password));
    if($row=$get_statement->fetch(PDO::FETCH_ASSOC)) // as we are getting only one record, therefore fetch() method is best. The fetchAll should be used if you are getting multiple records
    {

        $jTableResult['Result'] = "OK";
        $jTableResult['Record'] = $row;
        print json_encode($jTableResult);

    }
    else
    {
        echo json_encode("Error");
    }

}
else
{
        $jTableResult['Result'] = "FAIL";
        $jTableResult['Record'] = array();
        print json_encode($jTableResult);
}       
?>

相关问题