我目前遇到一個問題,當我嘗試使用 PHP 將 CSV 檔案中的資料插入 MySQL 資料庫時,出現由 CSV 檔案中的空欄位引起的錯誤。
在至少有一個空欄位的每一行資料中,它會產生一個錯誤,并且由于空欄位而不會將整行插入到資料庫中。
我想知道是否有人知道如何在 CSV 檔案中找到每個空欄位并在插入它們之前填充它們(“0”表示空 int 欄位,“N/A”表示空 varchar 欄位)而不通過 CSV 檔案和填充在資料中手動。
將資料插入資料庫的代碼
foreach($gymarr as $row){
$day = $row[0];
$routine= $row[1];
$time= $row[2];
$type= $row[3];
$run= $row[4];
$weights= $row[5];
$tally= $row[6];
$sqlinsert = "INSERT INTO Gym (day, routine, time, type, run, weights, tally)
VALUES ('$day', '$routine', $time, '$type', '$run', '$weights', tally)";
$result = $conn->query($sqlinsert);
uj5u.com熱心網友回復:
空值對 sql 插入有效。錯誤
“您的 SQL 語法有錯誤;請檢查與您的 MariaDB 服務器版本相對應的手冊,以了解在第 4 行附近使用的正確語法“'50kg')'”
意味著由于語法,值本身正在破壞您的查詢。如果您系結這些值,那么資料庫會將查詢和值分開,并且您的源不應再破壞這些值。Mysql 允許空的''.
解決問題的正確、最佳和最安全的方法是使用系結引數。我幾年前撰寫的以下函式為我簡化了這種型別的作業,它們可以防止 sql 被值污染。
職能:
function dbConnect($dbname,$username,$password,$servername = "localhost"){
if(empty($dbname) || empty($username) || empty($password)) return "Undefined database, username or password.";
try {
$conn = new PDO("mysql:host=$servername;charset=utf8;dbname=".$dbname, $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
$conn->setAttribute(PDO::MYSQL_ATTR_LOCAL_INFILE, true);
return $conn;
}
catch(PDOException $e){
return "Connection failed: " . $e->getMessage();
}
}
function dbQuery($conn,$sql="", $parameters=array(),$constant = PDO::FETCH_ASSOC){
try{
$stmt = $conn->prepare($sql);
} catch(PDOException $e){
return $e;
}
foreach($parameters as $key=>$value) $stmt->bindValue( $key 1, $value);
try{
$stmt->execute();
if ($stmt->columnCount() > 0){
$result = $stmt->fetchAll($constant); //in cases of select something, return the rows.
} else {
$result = $stmt->rowCount();//in case of update/insert/delete statements: get number of rows affected
}
} catch(PDOException $e){
$result = $e->getMessage();
}
return $result;
}
編碼:
$conn = dbConnect($dbname,$username,$password,$servername);//you have to populate these values yourself
foreach($gymarr as $row){
$sql = "INSERT INTO Gym (day, routine, time, type, run, weights, tally)
VALUES (?, ?, ?, ?, ?, ?, ?)";
$result = dbQuery($conn, $sql,$row);//row is any flat, two dimensional array. It must have the same number of values as the number of '?' in your sql for each one to bind to and in the order that those columns appear in your query.
}
如果您更喜歡 MySQLi 作為您的資料庫連接,請參閱https://www.w3schools.com/php/php_mysql_prepared_statements.asp。
uj5u.com熱心網友回復:
也許這種方式對你有用:
$day = $row[0] !== "" ? $row[0] : "n/a";
$routine= $row[1] !== "" ? $row[1] : "n/a";
$time= $row[2] !== "" ? $row[2] : "n/a";
$type= $row[3] !== "" ? $row[3] : "n/a";
$run= $row[4] !== "" ? $row[4] : "n/a";
$weights= $row[5] !== "" ? $row[5] : "n/a";
$tally= $row[6] !== "" ? $row[6] : "n/a";
如果需要,您可以將“n/a”替換為“0”。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/329515.html
