How can the use of print() and mysql_error() help troubleshoot PHP code that is not correctly handling negative values from a CSV file?
When PHP code is not correctly handling negative values from a CSV file, using print() statements can help to identify where the issue is occurring in the code. Additionally, using mysql_error() can help to pinpoint any errors that may be related to inserting negative values into a database. By strategically placing print() statements and checking for mysql errors, the root cause of the problem can be identified and resolved.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$file = fopen("data.csv", "r");
while (($data = fgetcsv($file, 1000, ",")) !== FALSE) {
$value = $data[0];
// Use print() to debug
print("Value from CSV: " . $value . "\n");
$sql = "INSERT INTO table_name (column_name) VALUES ('$value')";
if ($conn->query($sql) === TRUE) {
echo "Record inserted successfully";
} else {
// Use mysql_error() to check for errors
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
fclose($file);
$conn->close();
?>