【发布时间】:2013-03-28 22:54:56
【问题描述】:
我是 php 的新手,我一直在尝试将一系列变量插入到 mysql 数据库中。但是,似乎在创建表时数据没有输入到表中。我希望有人能告诉我为什么。任何帮助将不胜感激。
php代码:
<?php
$team = $_POST['team'];
$int1 = $_POST['int1'];
$int2 = $_POST['int2'];
$int3 = $_POST['int3'];
$int4 = $_POST['int4'];
$int5 = $_POST['int5'];
$int6 = $_POST['int6'];
$int7 = $_POST['int7'];
$int8 = $_POST['int8'];
$int9 = $_POST['int9'];
$int10 = $_POST['int10'];
$int11 = $_POST['int11'];
$int12 = $_POST['int12'];
$int13 = $_POST['int13'];
$int14 = $_POST['int14'];
$con=mysqli_connect("127.0.0.1:3306","root","password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sqli="CREATE TABLE $team(int1 INT,int2 INT,int3 INT,int4 INT,int5 INT,int6 INT,int7 INT,int8 INT,int9 INT,int10 INT,int11 INT,int12 INT,int13 INT,int14 INT)";
if (mysqli_query($con,$sqli))
{
echo "<br />Table created successfully";
}
else
{
echo "<br />Error creating table: " . mysqli_error();
}
$sql="INSERT INTO $team (int1, int2 ,int3 ,int4 ,int5 ,int6 ,int7 ,int8 ,int9 ,int10 ,int11 ,int12 ,int13 ,int14 )
VALUES ($int1,$int2,$int3,$int4,$int5,$int6,$int7,$int8,$int9,$int10,$int11,$int12,$int13,$int14)";
if (mysqli_query($con,$sql))
{
echo "<br />Record added";
}
else
{
echo "<br />Error adding record";
}
?>
【问题讨论】:
-
为什么不管结果如何都检查连接是否失败?
-
你遇到了什么错误?
-
在使用 $team 的同名文件两次或更多次启动此 .php 后,无论如何,您肯定会收到错误消息,因为该表已经创建。因此,您应该更改为 CREATE TABLE IF NOT EXISTS 甚至更好:不要通过 php 创建表 - 通过 mysql cli 创建它们 - 这称为数据库设计部分 ;-)
-
并且请将这些变量和列名更改为重要的,如果它只是用于测试 3 就可以了。答案:由于缺少引号 VALUES ('$int1', ...),它不起作用 - 我想你可以通过简单的谷歌搜索看到:“mysqli documentation insert into with variables”
标签: php mysql database insert mysqli