连接数据库并插入数据 - Php& MySQL -

时间:2015-09-09 06:16:38

标签: php mysql mysqli

我开始研究php和mysql,我从这个简单的模块开始,包括:

  
      
  1. 创建数据库连接; (运行)
  2.   
  3. 连接到DataBase; (不提供输出信息,可能不起作用)
  4.   
  5. 插入数据; (不工作)
  6.   

问题:
为什么它不能正常工作?

我创建了这个简单的PHP页面(文件名: inizio.php ):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta content="it" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Pagina di inizio</title>
</head>

<body style="width: 672px; height: 289px">

<p class="auto-style1" style="width: 293px; height: 24px">Titolo centrato della pagina</p>
        <form method="post" action="inserimento.php" style="width: 674px; height: 130px">
        Inserisci il nome:<input name="nome" type="text" /><br />
        Inserisci il cognome:<input name="cognome" type="text" /> <br />
        <br />
        <input name="Submit1" type="submit" value="Invia" /><br />
    </form>
</body>
</html>

创建此php脚本后(文件名 inserimento.php ):

<?php
$host='localhost';
$user='root';
$password='root';
$database='test_youtube';

// 1. Create a database connection
$connection = mysqli_connect($host,$user,$password);
if (!$connection)
{
    die("Database connection failed: " . mysqli_error());
}
else
{
    die("...Connesso con successo al Server!");
}

// 2. Select a database to use 
$db_select = mysqli_select_db($connection, $database);
if (!$db_select)
{
    die("Database selection failed: " . mysqli_error());
}
else 
{
    die("...Connesso con successo al Database!");
}

$query="insert into users(firstname, lastname)VALUES('".$_REQUEST['nome']."','".$request['cognome']."')";
if (!mysqli_query($query,$db_select))
{print("errore inserimento dati");
}
?>

2 个答案:

答案 0 :(得分:0)

在php文件中尝试die(),如下所示:

$connection = mysqli_connect($host,$user,$password,$database);

/* check connection */
if (mysqli_connect_errno()) {
    die("Connect failed: ", mysqli_connect_error());
}

$query="insert into users(firstname, lastname)VALUES('".$_REQUEST['nome']."','".$_REQUEST['cognome']."')";
if ($result = mysqli_query($connection ,$query))
{
    print("Success!");
}

答案 1 :(得分:0)

$con=mysqli_connect("localhost","root","root","test_youtube");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

// Perform queries 

mysqli_query($con,"INSERT INTO data_entry_users (user_name,user_password) VALUES ('".$_REQUEST['nome']."','".$_REQUEST['cognome']."')");
mysqli_close($con);