php - error insert into mysqli database -
i have insert data mysqli database
<?php $servername = "localhost"; $username = "xxxxx"; $password = "xxxxx"; $dbname = "xxxxx"; $url = "http://$_server[http_host]$_server[request_uri]"; $ip_address = $_server['remote_addr']; $last_url = $_server['http_referer']; // create connection $conn = new mysqli($servername, $username, $password, $dbname); // check connection if ($conn->connect_error) { die("connection failed: " . $conn->connect_error); } $sql = "insert url_referer (url_referer, ip address, current_url) values ('$last_url', '$ip_address', '$url')"; if ($conn->query($sql) === true) { echo " "; } else { echo "error: " . $sql . "<br>" . $conn->error; } $conn->close(); ?>
i keep getting error:
error: insert url_referer (url_referer, ip address, current_url) values ('', '72.69.102.254', 'http://bithumor.co/') have error in sql syntax; check manual corresponds mysql server version right syntax use near 'address, current_url) values ('', '72.69.102.254', 'http://bithumor.co/')' @ line 1
how fix this?
if column name indeed contain space ip address
needs wrapped in ticks or rename column name have undercore.
(url_referer, `ip address`, current_url)
or rename it
(url_referer, ip_address, current_url)
then won't need ticks.
however, ticks required if contains mysql reserved word, or hyphen, or else complain about.
sidenote: noticed have both table , column bearing same name url_referer
. make sure in fact case.
plus, per comment:
- sidenote
$_server['http_referer']
. isn't reliable. - read following: https://stackoverflow.com/a/6023980/
another thing. if still gives problems, need escape data.
i.e.:
$last_url = $_server['http_referer']; $last_url = mysqli_real_escape_string($conn, $last_url);
and apply logic variables inserted in table.
your present code open sql injection. use prepared statements, or pdo prepared statements, they're safer.
mysqli prepared statements example:
<?php $link = new mysqli('xxx', 'xxx', 'xxx', 'xxx'); if ($link->connect_errno) { throw new exception($link->connect_error, $link->connect_errno); } // check expected value has been provided via post request if (!isset($_post['input'])) { throw new exception('missing post request parameter [input]'); } // prepare insert statement if (!$stmt = $link->prepare('insert `table` (`column_x`) values (?)')) { throw new exception($link->error, $link->errno); } // bind parameters $stmt->bind_param('s', $_post['input']); if (!$stmt->execute()) { throw new exception($stmt->error, $stmt->errno); }
add error reporting top of file(s) find errors.
<?php error_reporting(e_all); ini_set('display_errors', 1); // rest of code
sidenote: error reporting should done in staging, , never production.
Comments
Post a Comment