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')";
3
  • 2
    Simple, you didn't execute the query. Commented Jul 4, 2017 at 20:31
  • 1
    execute the $sql that's it. $mysqli->query($sql); Commented Jul 4, 2017 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! Get started with mysqli::prepare() and mysqli_stmt::bind_param(). Even though these values currently are static - they're most likely to change later on, I assume? Commented Jul 4, 2017 at 20:35

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Do try and avoid things like === TRUE, it sets up bad habits. In this case if ($conn->query(...)) is sufficient.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.