Inserting into database using a PDO

后端 未结 4 1073
借酒劲吻你
借酒劲吻你 2021-01-23 02:08

I\'m trying to insert data into a database that I have on my server.

To connect to my database I have the following code:



        
4条回答
  •  天命终不由人
    2021-01-23 03:02

    you are opening two database connection. change your code to

    $host = "/homes/49/jc192699/public_html/dbase/";
    $database = "EduPro.db";
    try {
        $conn = new PDO("sqlite:".$host.$database);
    } catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage();
    }
    

    you should not use backquote instead using single quote in your query. and also column should not have any quotes.

    try {
        $sql = "INSERT INTO USERS (userName, password) VALUES ('test', 'testy')";
        $sth = $conn->query($sql);
    } catch(PDOException $e) {
        echo $e->getMessage();
    }
    

    to fetch the records you need to use this

    try {
        $sth = $conn->query('SELECT * FROM USERS');
        $rows = $sth->fetchAll(PDO::FETCH_ASSOC);
        //$rows contains the fetched records in an associative array
        var_dump($rows);
    } catch(PDOException $e) {
        echo $e->getMessage();
    }
    

    learn more about PDO here http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/

提交回复
热议问题