简体   繁体   English

mysql - 无法使用 php 将数据插入数据库

[英]mysql - can't insert data into database with php

I'm tryin to add users to my MYSQL database with PHP, somehow it is not working.我正在尝试使用 PHP 将用户添加到我的 MYSQL 数据库中,但不知何故它不起作用。 Check my script below.在下面检查我的脚本。 What am i doing wrong?我究竟做错了什么?

<html>
<head>
</head>
<body>
<form action="index2.php" method="post">
Voornaam: <input type="text" name="voornaam"><br />

<input type="submit" name="submit">
</form>

<?php
if (isset($_POST['submit'])) {

$con = mysql_connect("localhost","hakan","hakan");
if (!$con) {
die ("Can not connect: " . mysql_error());
}

mysql_select_db("projectfys",$con);

$sql = "INSERT INTO gebruikers (voornaam) VALUES ('voornaam')";

mysql_query($sql,$con);

mysql_close($con);
}
?>

</body>
</html>

$con needs to be in first place $con 需要排在第一位

Eg例如

mysql_select_db($con,'db');
mysql_query($con,$sql);

Change the direction everywhere.到处改变方向。

Also, change everything to mysqli, you can find masses of tutorials for mysqli or PDO此外,将所有内容更改为 mysqli,您可以找到大量的 mysqli 或 PDO 教程

This block should look like (with mysqli):这个块应该看起来像(使用 mysqli):

$con = new mysqli("localhost","hakan","hakan","projectfys");
 $con -> set_charset ( 'utf8' );
            if ($con->connect_errno) {
            printf("Connect failed: %s\n", $con->connect_error);
            exit();}


mysqli_query($con, "INSERT INTO gebruikers (voornaam) VALUES ('voornaam')");



$con -> close();

EDIT编辑

With your query, you will allways insert the string "voornaam" in your table.通过查询,您将始终在表中插入字符串“voornaam”。

You need to do this before:您需要在此之前执行此操作:

$voornaam = $_POST['voornaam'];
$voornaam = mysqli_real_escape_string($con,$voornaam);

Add this after your connection and before the query.在您的连接之后和查询之前添加它。 In the query, replace the second 'voornaam' with '$voornaam'在查询中,将第二个 'voornaam' 替换为 '$voornaam'

mysqli_query($con, "INSERT INTO gebruikers (voornaam) VALUES ('$voornaam')");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM