我的列标题是ID,名称,电话。如果我在id列中输入了名称,则数据不会插入,但消息显示为“成功导入”。我想显示类似“数据未正确定义”的消息。在导入mysql之前如何验证代码?
我尝试检查if和else条件,但没有得到我需要的实际结果。
selectByFoosAndBars(foosAndBars: Iterable<PairType>): Iterable<Thing>
我希望警报消息为“数据不正确”,但获得“成功导入”。
答案 0 :(得分:0)
您可以使用is_int()来检查值(在您的情况下为$ getData [0])是否为整数。
在查询中添加值之前
if(!is_int($getData[0])
{
echo "<script type=\"text/javascript\"> alert(\"Improper Data.\");
}</script>";
}
else
{
// insert query code here
}
答案 1 :(得分:0)
验证应该在任何INSERT之前完成,这样您就可以做到:
<?php
//validation of csv
if (false === validateCsvRow($getData)) {
echo "data is not properly defined";
// or better to throw an exception - uncomment to see difference
// throw new \InvalidArgumentException("data is not properly defined");
die; //end script execution
}
// if validation is okay script continues.
$sql = "INSERT IGNORE INTO `all`(`id`, `name`,`phone`) VALUES ('".$getData[0]."','".$getData[1]."','".$getData[2]."')";
$result = mysqli_query($conn, $sql);
if($result)
{
echo "<script type=\"text/javascript\">alert(\"CSV File has been successfully Imported.\");
}</script>";
else {
echo "<script type=\"text/javascript\"> alert(\"Invalid File Format/ Data Please check file is csv and data as per headings.\");
}</script>";
}
function validateCsvRow(array $data) : bool
{
$result = 1;
//check if id is not set
if (!isset($data[0]) {
$result *= 0;
}
//check if id is not integer
if (!is_int($data[0]) {
$result *= 0;
}
//check if name is not set
if (!isset($data[1]) {
$result *= 0;
}
//check if name is not string
if (!is_string($data[1]) {
$result *= 0;
}
$minimumNameLength = 1; //number of characters
//check if name has at least n characters
if (!strlen($data[1]) < $minimumNameLength) {
$result *= 0;
}
//return 1 => true if all was ok
//or 0 => false if at least one check was not ok.
return (bool) $result;
}
如果您使用的是旧的php版本更改,则上面的代码将使用键入内容
function validateCsvRow(array $data) : bool
收件人:
function validateCsvRow($data)
答案 2 :(得分:0)
CSV中的字段顺序可能有所不同,例如。列0不能总是“ id”。
考虑此CSV:
name, id, phone
'Alice', 1, 1234
'Bob', 2, 5678
和此代码:
$sql = "INSERT IGNORE INTO `all`(`id`, `name`,`phone`) VALUES (?, ?, ?)";
$stmt = $db->prepare($sql);
$header = null;
while($row = fgetcsv($handle)) {
if ($header == null) {
$header = $row;
continue;
}
$data = array_combine($header, $row);
// $data is now an assoziative array, eg. you can grab "id" by name
$stmt->execute([ $data['id'], $data['name'], $data['phone'] ]);
}