Andre Andre Rotaru Andre Andre Rotaru - 6 months ago 17
SQL Question

PHP script not writing data into database

I have this code from another Stack Overflow question answered here.

I have a mysql table called track in my database.

$server = "host";
$username = "user";
$password = "pass";
$database = "database";

$connId = mysql_connect($server,$username,$password) or die("Cannot connect to server");
$selectDb = mysql_select_db($database,$connId) or die("Cannot connect to database");

$host_name = gethostbyaddr($_SERVER['REMOTE_ADDR']);
$strSQL = "INSERT INTO track (tm, ref, agent, ip, tracking_page_name, host_name) VALUES(curdate(),'$ref','$agent','$ip','$tracking_page_name','$host_name')";

Basically I want all the data this script collects to be put into my database. However, no matter what I type, even if I change the variables to text, nothing gets written into the database. I can read from the database just fine using another script, but I can't get this one to add any piece of info to the db. Is there a typo I just can't seem to find?

I just want information about anyone who visits the page this gets included in.

EDIT: I was trying to fill a field called "host_name", but in my database it had a different name. The original script shown here would not show the error and I did not ever run a check to see if all my fields are in order. That was the error.


Many possibilities:

  1. If the user user has read permissions but not write permissions on the database or the table, read ops will succeed but write ops will fail.
  2. If this is a MyISAM table, the table may be locked by another process. Read operations would work but write operations would not
  3. Maybe the table or a field you're trying to write to does not exist or is misspelled




if(!$test=mysql_query($strSQL)) die(mysql_error());

It will show you why the operation failed (docs).

Also, if you're starting don't use MySQL functions. They are being removed from PHP so you're just giving yourself more work to do in the future. Use MySQLi or PDO_MySQL instead (docs).

Finally, never just insert text you got from the browser in an SQL query. The values of $_SERVER['HTTP_REFERER'] and $_SERVER['HTTP_USER_AGENT'] can be manipulated by your user to be anything, including a string that causes you to execute whatever query the user wants (delete your tables, exfiltrate your data...). Learn about prepared statements and parameterized queries and use them instead