连接数据库php

时间:2017-01-31 14:43:01

标签: php mysqli

连接数据库的正确方法是什么?我没有收到错误但也许我的连接没有正确使用我使用mysqli 这是我的代码

 <?php 
 require_once("configur.php");

 $mysqli = new mysqli(localhost, root, password, user);

 $query_image = 'INSERT INTO fun_table (images1, images2, images3, images4) 
values( "' . $_FILES['file1']['name'] . '",
        "' . $_FILES['file2']['name'] . '",
        "' . $_FILES['file3']['name'] . '",
        "' . $_FILES['file4']['name'] . '"
   )';


   if ($mysqli->query($query_image) === TRUE) {

   echo "<script language='javascript'>\n";
   echo "alert('Upload successful!')";
   echo "</script>\n";
 } else {
  echo "Error updating record: " . $conn->error;
 }

    $mysqli->close();

   ?>

2 个答案:

答案 0 :(得分:1)

$ mysqli = new mysqli(localhost,root,password,user);

您需要定义它们或将它们放在引号中。

像:

$servername = 'localhost';
$username = 'user123';
$password = 'helloworld';
$dbname ="testdatabase";

 $conn = mysqli_connect($servername, $username, $password, $dbname);

或者

 $conn = mysqli_connect("localhost", "user123", "helloworld", "testdatabase");

答案 1 :(得分:0)

mysqli已过时,请勿使用。相反,您可以使用PDO进行连接,例如:

<?php
    try
    {
        $db = new PDO("mysql:host=".localhost."; dbname=".db_name, root, "");
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO:: ERRMODE_EXCEPTION);
    }
    catch (PDOException $exception)
    {
        die('Error: '.$exception);
    }
?>