Jump to content

How To Insert New Row If Conditions Are Meet ?


phpBeginner06

Recommended Posts

I am trying to automatically insert a new row into data table; if there is no row with specific field value. But the code I have written below is not doing anything at all.

Where Am I Going Wrong With This Code?

[code]<?php
mysql_connect("localhost","username","password");
mysql_select_db("Statistics");
$page = $_SERVER['PHP_SELF'];
$look4 = "SELECT * FROM hitsTable WHERE page = '$page'";
$check = mysql_query($look4);

if(mysql_num_rows($check) == 0){
mysql_query("INSERT INTO `hitsTable` (visits, page) VALUES ('1', '$page')");
}else
{
echo "logged";
}
}
?>[/code]
You should always check your query actually succeeds before trying to use any result. (Also, note the indentation)

[code]
<?php
  mysql_connect("localhost","username","password");
  mysql_select_db("Statistics");
  $page = $_SERVER['PHP_SELF'];
  $sql = "SELECT * FROM hitsTable WHERE page = '$page'";
  if ($result = mysql_query($sql)) {
    if (!mysql_num_rows($result)) {
      if ($result = mysql_query("INSERT INTO hitsTable (visits, page) VALUES (1, '$page')")) {
        echo "Insert success";
      } else {
        echo "Insert failed ".mysql_error();
      }
    }
  } else {
    echo "Select failed ".mysql_error();
  }
?>
[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.