skip to Main Content

I was trying to insert values to MySQL database with following code:

$pdo = new PDO('mysql:host=localhost;dbname=project;charset=utf8;, 'admin', 'password');
$stmt = $pdo->prepare('INSERT INTO userdata values(?, ?, ?, ?, ?)');
if ($stmt->execute(null, '"'.$_REQUEST['username'].'"', '"'.$_REQUEST['password'].'"', '"'.$file.'"', null)) {
echo 'Inserted'
} else {
print_r ($stmt -> errorInfo());
}

However, when I run this code, the output says:

Array ( [0] => [1] => [2] => )

and I can’t add any values to the MySQL database.
I made the MySQL database with followinig code:

drop database if exists project;
create database project character set utf8 collate utf8_general_ci;
grant all on project.* to 'admin'@'localhost' identified by 'password';
use project;

create table userdata (
userid int auto_increment primary key,
username varchar(30) not null,
password varchar(30) not null,
avatar varchar(30) not null,
profilepage varchar(30)
);

Any solutions?

2

Answers


  1. PDOStatement::execute accepts one parameter of type array. (Read)

    Try this way

    $stmt->execute([null, '"'.$_REQUEST['username'].'"', '"'.$_REQUEST['password'].'"', '"'.$file.'"', null])
    
    Login or Signup to reply.
  2. You want something like this.

    $pdo = new PDO('mysql:host=localhost;dbname=project;charset=utf8;', 'admin', 'password');
    $stmt = $pdo->prepare('INSERT INTO userdata (username, password, avatar, profilepage)
            values(?, ?, ?, ?)');
    if ($stmt->execute([$_REQUEST['username'], $_REQUEST['password'], $file, null])) {
    echo 'Inserted'
    } else {
    print_r ($stmt -> errorInfo());
    }
    
    1. execute needs an array, hence the []
    2. userid is autoincrement, so there is no need to pass it
    3. You have to tell it the fieldnames that correspond with the values
    4. You don’t need the extra quotes.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search