This question already has an answer here:
Here is my code:
$username = $connection->real_escape_string($username);
$html = $connection->real_escape_string($html);
$query = $connection->query("SELECT * from savedarticles WHERE username = '$username' AND article = '$html'");
$matches = mysqli_num_rows($query);
if ($matches == 0) {
$connection->query("INSERT INTO savedarticles ('username', 'article') VALUES ($username, $html)");
}
if ($matches == 1) {
$row = mysqli_fetch_array($query);
$connection->query("DELETE FROM savedarticles WHERE username = '$username' AND article='$html'");
}
My table name is same in the PHP code and PHPMYADMIN section. I have created two columns with name username
and article
in the table. This code however, does not insert a new row. The table is empty with no rows. Also, is there a way to delete a row directly since I have already singled it out (instead of running the query through whole table again).
</div>
Change this line like this. You dont need to use single quotes for column name
$connection->query("INSERT INTO savedarticles (username, article) VALUES ('$username', '$html')");
You are adding single quotes against field names, which is incorrect.
Change:
$connection->query("INSERT INTO savedarticles
('username', 'article') VALUES ($username, $html)");
To:
$connection->query("INSERT INTO savedarticles
(username, article) VALUES ('$username', '$html')");
You can use backtick (`) against field names to avoid conflict with MySQL reserved keywords.
Example is as following:
$connection->query("INSERT INTO savedarticles
(`username`, `article`) VALUES ('$username', '$html')");
But, single quotes means user entered string and it will not refer to any DB name, table name or field name.