How to connect php to mysql database?

前端 未结 2 708
礼貌的吻别
礼貌的吻别 2021-01-15 16:05

I\'m making a search engine for a website and I\'ve never used PHP before and I have been trying to connect my webpage to a mysql database using this code:

          


        
相关标签:
2条回答
  • 2021-01-15 16:43

    This is explained at http://php.net/manual/en/function.mysql-connect.php

    You should use one of the extensions: MySQLi or PDO_MySQL

    With MySQLi you basically add an i to the new version of your code (do not use the old code) further information can be found here: http://php.net/manual/en/function.mysqli-connect.php. Otherwise please look at http://php.net/manual/en/pdo.construct.php

    Hope this helps.

    0 讨论(0)
  • 2021-01-15 16:47

    here you go, using PDO.

    define("SQLHOST", "127.0.0.1");
    define("SQLUSER", "login");
    define("SQLPASS", "password");
    define("SQLSGBD", "database");
    
    $conn = new PDO('mysql:host=' . SQLHOST . ';dbname=' . SQLSGBD . ';charset=UTF8', SQLUSER, SQLPASS);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql1 = 'SELECT * FROM table where field1=?';
    $stmt1 = $conn->prepare($sql1);
    
    $field1="test";
    $stmt1->bindParam(1, $field1, PDO::PARAM_STR);
    
    try {
        $stmt1->execute();
        $result = $stmt1->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        if ($showError === true) {
            var_dump("error query 1:" . __LINE__ . "-------" . __FUNCTION__ . "-------" . $e->getMessage());
            exit;
        }
    }
    
    0 讨论(0)
提交回复
热议问题