简体   繁体   中英

Creating and Updating User Table With PHP/MySql Script

I am reading a book on PHP, MYSQL, JAVASCRIPT and JQUERY. While reading, I do type the code and see how it worked. I have the following script which I ran to create a table named: "users', and subsequently update the table with two users. When I ran the script in my browser, it only created the new table but failed to update it with the new users. I do not receive any error. Below is the entire script.

<?php // setup_users.php 

require_once 'login.php';

$connection = new mysqli($hn, $un, $pw, $db);
if ($connection->connect_error) die($connection->connect_error);

$query = "CREATE TABLE users (

    forename VARCHAR(32) NOT NULL,
    surname  VARCHAR(32) NOT NULL,
    username VARCHAR(32) NOT NULL UNIQUE,
    password VARCHAR(32) NOT NULL
    )";

$result = $connection->query($query);

if (!$result) die($connection->error);

$salt1 = "qm&g";
$salt2 = "ph!@";

$forename = 'Baban';
$surname = 'Sadik';
$username = 'bsadik';
$password = 'babansadik1';
$token = hash('ripemd128', "$salt1$password$salt2");

add_user($connection, $forename, $surname, $username, $token);

$forename = 'Abdullah';
$surname = 'Abubakar';
$username = 'aabubakar';
$password = 'abakar1';
$token = hash('ripemd128', "$salt1$password$salt2");

add_user($connection, $forename, $surname, $username, $token);

function add_user($connection, $fn, $sn, $un, $pw) {

    $query = "INSERT INTO users VALUES('$forename', '$surname', '$username', '$token')";
    $result = $connection->query($query);
    if (!$result) die($connection->error);

}

?>

Where did go wrong please?

Your add_user function has parameters different to what you are trying to use in the query itself.

Change the query to the following:

INSERT INTO users VALUES('$fn', '$sn', '$un', '$pw')

Note that you should use prepared statements instead, as currently the code is susceptible to SQL Injection attacks. If the book you're using doesn't contain information on using prepared statements, scrap the book and find one that does instead.

You just missed to put column names in the insertion query in add_user function and you are passing undefined variables Do like this

$query = "INSERT INTO users(forename, surname, username, password)
        VALUES('$fn', '$sn', '$un', '$pw')";

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