我是PHP编程的新手。所以我不明白为什么我的代码不起作用(并且没有显示任何错误) 我想在我的表sinhvien中插入新记录 这是我的代码:
<?php
$con=new mysqli("localhost","root");
$con->select_db('learn_mysql');
$query="INSERT INTO sinhvien (ho,ten,tuoi) VALUES ('le','van cuong',26)";
$con->query($query);
$con->close();
?>
运行正常但没有记录插入我的表格。
答案 0 :(得分:1)
您没有正确连接,请尝试以下操作:
<?php
$servername = "localhost";
$username = "root";
$password = "YOURS";
$dbname = "learn_mysql";
$conn = new mysqli($servername, $username, $password, $dbname);
if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); }
$sql = "INSERT INTO `sinhvien`(`ho`, `ten`, `tuoi`) VALUES ('le','van coung','26')";
if ($conn->query($sql) === TRUE) { } else {echo "Error: " . $sql . "<br>" . $conn->error;}
$conn->close();
?>
答案 1 :(得分:0)
我建议你浏览一些php mysqli基础教程。另请尝试使用mysqli in a object oriented way with mysqli Prepared statements
。
以下是我的两个例子
0)使用MYSQLI连接到数据库
<?php
$localhost='localhost';
$username='root';
$password='admin';
$databaseName='example';
$con = new mysqli($localhost,$username,$password,$databaseName);
if(mysqli_connect_errno()){
die("connection Failed: ".mysqli_connect_errno());
}
1)MYSQLI OBJECT OREINTED WAY
//THIS IS ONE OF THE WAYS OF INSERTING DATA IN MYSQL USING MYSQLI
$sql="INSERT INTO sinhvien (ho,ten,tuoi) VALUES ('THIS','WAY ALSO WORKS',26)";
if($con->query($sql) === TRUE){
echo "INSERTED INTO THE DATA BASE";
}
2)以MYSQLI准备语句为导向的MYSQLI对象
//THIS IS ONE OF THE WAYS OF INSERTING DATA IN MYSQL USING MYSQLI PREPARED STATEMENT WHICH IS MORE SECURE AGAINST MYSQL INJECTION
$query=$con->stmt_init(); //INITIATE
$a='THIS IS';
$b='MYSQLI PREPARED STATEMENT';
$c=30;
if($query->prepare("INSERT INTO sinhvien(ho,ten,tuoi)VALUES(?,?,?)")){
$query->bind_param('ssi',$a,$b,$c);//BIND THE ? TO THES VARIABLES
$query->execute();//NOW EXECUTE THEM
echo "INSERTED INTO THE DATABASE WITH MYSQLI PREPARED STATEMENT";
}
?>