Reputation: 1650
I'm using variables to record information about website users, to observe their behaviour on my site. My code looks like this:
<?php
$pages_visited = "www.example.com, www.example.com/example.php, www.example.com/demo.php";
$con = mysqli_connect("localhost", "user", "password", "pages_visited");
if (mysqli_connect_errno()) {
echo "An error occurred when connecting to the database. Sorry.";
}
mysqli_query($con, "INSERT INTO visit_data ('Pages')
VALUES ('$pages_visited')");
mysqli_close($con);
Though, when I visit my website, nothing happens, and no new rows are added in the table visit_data. Why is this happening?
Upvotes: 0
Views: 66
Reputation: 375
You need to update your query:
INSERT INTO visit_data (`Pages`) VALUES('".$pages_visited."')
Actually you are using Single quote('Pages'), check bellow code. I have verified this code locally its running
<?php
$pages_visited = "www.example.com, www.example.com/example.php, www.example.com/demo.php";
$con = mysqli_connect("localhost", "user", "password", "pages_visited");
if (mysqli_connect_errno()) {
echo "An error occurred when connecting to the database. Sorry.";
}
$try = mysqli_query($con, "INSERT INTO visit_data (`Pages`) VALUES('".$pages_visited."')");
if($try === false){
echo 'error - ';
echo mysqli_error($con);
} else{
echo 'all good';
}
mysqli_close($con);
Upvotes: 1
Reputation: 353
You gotta use '". $text_var . "' when using strings. Make sure that the table column your using is correct and that your not leaving out any columns that don't accept a null value unless you used default on table creation.
this should work
<?php
$pages_visited = "www.example.com, www.example.com/example.php, www.example.com/demo.php";
$con = mysqli_connect("localhost", "user", "password", "pages_visited");
if ( mysqli_connect_errno() )
{
echo "An error occurred when connecting to the database. Sorry.";
}
mysqli_query( $con, "INSERT INTO visit_data ( Pages ) VALUES ( '" . $pages_visited . "' )" );
mysqli_close($con);
Upvotes: -1
Reputation: 618
try mysqli prepared statements(the error is not associated with not using prepared statements but I thought it would be better to use since mysql functions are deprecated)
$db = new mysqli('localhost', 'root', '', 'database');
if ($db->connect_errno) {
echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}
$pages_visited = "www.example.com, www.example.com/example.php, www.example.com/demo.php";
$stmt = $db->prepare("insert into `visit_data` (Pages) values(?)");
$stmt->bind_param('s', $pages_visited);
$stmt->execute();
Upvotes: 1