0

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).

SanJeet Singh
  • 1,291
  • 2
  • 15
  • 28

2 Answers2

0

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')");
Arun Krish
  • 2,153
  • 1
  • 10
  • 15
0

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.

Reference:

Pupil
  • 23,834
  • 6
  • 44
  • 66