简体   繁体   中英

It is not inserting data but it says "yes"

I tried this code

<?
$link = mysqli_connect('localhost', 'root', '123');
if (!$link) {
    die('Could not connect: ' . mysqli_error());
}
if(isset($_POST['Murad'])){
$db_selected = mysqli_select_db($link,'websiteusers' );
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$userName=$_POST['username'];
$password=$_POST['pwd1'];
$email=$_POST['email'];

$sqlb = "INSERT INTO websiteusers (fullname,lastname,userName,password,email)
VALUES ('$firstname', '$lastname', '$userName', '$password', '$email')";
if(mysqli_query($link,$sqlb)){
            echo "no";
}else {
    echo "yes";
}
 mysqli_close($link);
}
?>

But it is not inserting data but echos "yes". Why it is not inserting i have checked all input names and column names it is not wrong

Yes, that's the expected behaviour. Your if-else statement looks like:

if(mysqli_query($link,$sqlb)) {
// display "no" if query is executed successfully
} else {
// display "yes" if query is not executed successfully
}

mysqli_query() will return false on failure, otherwise it will return mysqli_result object or true on success.

So, just swap the positions of "yes" and "no" and if you're still wondering why it's not working, use the following line in your else statement :

echo mysqli_error($link);

如果它回显“是”,那么它不会插入数据,对吗?

You should use prepeared Statements, you avoid SQL Injections and it's easier to maintain the code if you change your database...

<?php
$servername = "localhost";
$username = "root";
$password = "123";
$dbname = "websiteusers";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$query = "INSERT INTO websiteusers (fullname, lastname, userName, password, email)
VALUES (?, ?, ?, ?, ?)";

// prepare and bind
$stmt = $conn->prepare($query);
$stmt->bind_param("sssss", $fullname, $lastname, $username, $password, $email);

// set parameters and execute
$fullname ="Donald Duck";
$lastname = "Duck";
$username = "donalod";
$password = sha1("DonaldDuck1!");
$mail = "donald@duck.com"
$stmt->execute();

$fullname ="Mickey Mouse";
$lastname = "Mouse";
$username = "mickey";
$password = sha1("IloveDaisy");
$mail = "mickey@mouse.org"
$stmt->execute();

echo "New records created successfully";

$stmt->close();
$conn->close();
?>

This example is copied from W3Schools and edited for your benefits.

More information about prepeared Statements: http://php.net/manual/en/pdo.prepared-statements.php

Trying this:

if(mysqli_query($link,$sqlb) === FALSE){
    echo mysqli_error($link);
}else {
    echo "yes";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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