我的更新脚本出现问题。基本上我在文本框中输入值,当我点击“添加”时,这些值会被添加到数据库中。
目前它允许我输入intergers并将这些添加到数据库中但是当我尝试添加文本时却没有。数据库字段类型设置为varchar(20),这是我的PHP代码:
public function insert($tableName,$fieldArray,$fieldValues) {
$pdo = new SQL();
$dbh = $pdo->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);
$this->sql = "INSERT INTO " . $tableName . " (".implode(',', $fieldArray).") VALUES (".implode(',', $fieldValues).")";
try {
// Query
$stmt = $dbh->prepare($this->sql);
$stmt->execute();
$count = $stmt->rowCount();
echo $count.' row(s) inserted by SQL: '.$stmt->queryString;
$stmt->closeCursor();
}
catch (PDOException $pe) {
echo 'Error: ' .$pe->getMessage(). 'SQL: '.$stmt->queryString;
die();
}
// Close connection
$dbh = null;
}
请让我知道我做错了什么! :)
答案 0 :(得分:2)
您需要将字段括在引号中。
将文字放在
中$text = "text"; //How you're doing it now
$text = "'text'"; //How you ought to (after sql escaping)
或试试这个:
$this->sql = "INSERT INTO " . $tableName . " (`".implode('`,`', $fieldArray)."`) VALUES ('".implode("','", $fieldValues)."')";
答案 1 :(得分:2)
将sql查询行更改为:
$this->sql = "INSERT INTO " . $tableName . " (`".implode('`, `', $fieldArray)."`) VALUES ('".implode("', '", $fieldValues) . "')";
问题是你没有用引号转义字符串。喜欢'someText'