0

I have a php code that needs to insert values in a db. However, when i run the script on the db it generates 2 rows with the same values. If i run the query directly on the db, it generates 1 row(as it is supposed to be). What's wrong with my code?

<?php

$id = htmlspecialchars($_GET["id"]);
$username = htmlspecialchars($_GET["username"]);
$score = htmlspecialchars($_GET["score"]);
$region = htmlspecialchars($_GET["region"]);
$elapsed_time = htmlspecialchars($_GET["elapsed_time"]);
$acquired_date = htmlspecialchars($_GET["acquired_date"]);

// Create connection
$conn = new mysqli("localhost", "root", "mypassword", "test");
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "INSERT INTO Utenti (username, region, score, elapsed_time, acquired_date) VALUES (".chr(34).$username.chr(34).",".chr(34).$region.chr(34).",".$score.",".chr(34).$elapsed_time.chr(34).",".chr(34).$acquired_date.chr(34).");";
$result = $conn->query($sql);

if ($conn->query($sql) === TRUE) {
    echo "Inserted";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?> 

and this is my table configuration:

    CREATE TABLE `Utenti` (
  `id` int(11) NOT NULL,
  `username` text COLLATE utf8_unicode_ci NOT NULL,
  `region` text COLLATE utf8_unicode_ci NOT NULL,
  `score` int(11) NOT NULL,
  `elapsed_time` time NOT NULL,
  `acquired_date` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

I load the variables like this:

my_url/insert.php?username=Example&region=France&score=200&elapsed_time=01:15:00&acquired_date=2018-11-30 22:40:00
Funk Forty Niner
  • 74,372
  • 15
  • 66
  • 132
Gabry
  • 35
  • 1
  • 8
  • 3
    `$result = $conn->query($sql);` **ONE** `if ($conn->query($sql) === TRUE) {` **TWO** –  Nov 30 '18 at 01:36
  • Thanks man, you deserve an upvote. Unfortunately i'm new to php so i didn't notice that. – Gabry Nov 30 '18 at 01:41

1 Answers1

0

You are indeed running the query two times in your code.

First just after declaring the SQL statement :

$result = $conn->query($sql);

Second in the if block :

if ($conn->query($sql) === TRUE) {

You would better use a construct like :

$status = $conn->query($sql);
if ($status === TRUE) {
    echo "Inserted";
...
GMB
  • 195,563
  • 23
  • 62
  • 110