简体   繁体   中英

How can i change my current mysqli procedural way into pdo where i can call store procedure

i'm currently using mysqli procedure to write code which i want to change it in pdo because in mysqli i'm mysqli_escape_string whereas i dont how to change it in pdo here is my mysqli attempt

<?php
    if(isset($_GET['id1'])){
        $id=$_GET['id1'];
        $result=GetWordsById(mysqli_escape_string($conn,$id));//Here GetWordsById is a function calling store procedure
        if(mysqli_num_rows($result)>0)
            $row=mysqli_fetch_array($result);
        $word=$row['word'];
        $meaning=$row['meaning'];
        $synonym=$row['synonym'];
        $antonym=$row['antonym'];


        }
    ?> 

below is my function.php

function GetWordsByID($id){
    include("conn.php");
    $result=mysqli_query($conn,"CALL GetWordsById($id)");//Here GetWordsById is my store procedure
    return $result;
}

Here i want to know how i can change both function and main php script calling function where i'm using mysqli_escape_string to pdo i'd appreciate some help

To PDO, your db connection file will look like this,

    <?
        $servername = "localhost";
    $username = "username";  // Enter your db username
    $password = "password";  // Enter your db password
    $dbname = "myDBPDO";   // Enter your db name

    try {
    $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully"; 
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }

    ?>

Now comes your code,

<?

   if(isset($_GET['id1'])){
        $id=$_GET['id1'];
        $result=GetWordsById($id);//Here GetWordsById is a function calling store procedure
        if($result->fetchColumn()>0){

            $row=$result->fetch(PDO::FETCH_ASSOC);
        $word=$row['word'];
        $meaning=$row['meaning'];
        $synonym=$row['synonym'];
        $antonym=$row['antonym'];


        }

}

and function,

function GetWordsByID($id){
    include("conn.php");
    $result=$conn->prepare("  ");//Here sql statement 
    $result->execute();
    return $result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM