0

I have very strange problem. I want to run mysql query as it is shown down below, but it's not working. Connection to database is successful, INSERT query is ok too, because when I run it directly in phpmyadmin Console it works, but it's not working here in PHP code.

Could you tell me what I'm missing?

$servername = "localhost";
$username = "admin";
$password = "admin123";
$dbname = "database1";

$conn = mysqli_connect($servername, $username, $password, $dbname);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO last_visit (ip, lastvisit) VALUES ('123', '123')";
Sergi Khizanishvili
  • 537
  • 1
  • 7
  • 16
  • 2
    Simple, you didn't execute the query. – Rajdeep Paul Jul 04 '17 at 20:31
  • 1
    execute the $sql that's it. $mysqli->query($sql); – Just_Do_It Jul 04 '17 at 20:32
  • 3
    You're already using an API that supports **prepared statements** with bounded variable input, you should utilize parameterized queries with placeholders (prepared statements) to protect your database against [SQL-injection](http://stackoverflow.com/q/60174/)! Get started with [`mysqli::prepare()`](http://php.net/mysqli.prepare) and [`mysqli_stmt::bind_param()`](http://php.net/mysqli-stmt.bind-param). Even though these values *currently* are static - they're most likely to change later on, I assume? – Qirel Jul 04 '17 at 20:35

1 Answers1

2

You need to run your $sql, because now your $sql is only a string, it does nothing.

Add this :

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
Alex Caron
  • 350
  • 3
  • 19
  • 2
    Do try and avoid things like `=== TRUE`, it sets up bad habits. In this case `if ($conn->query(...))` is sufficient. – tadman Jul 04 '17 at 20:39