我是PHP的新手,需要帮助为我的网站编写添加脚本。我编写了删除和更新方面的代码,它们工作正常。基本上,在我的网站的部分,您可以添加值到几个文本框,我想要的是,当您单击“添加”时,这将添加文本框中的详细信息到数据库。为此,我使用PHP,Jquery和Ajax。
这是我对更新脚本的代码:
public function update($tableName,$fieldArray,$fieldValues,$rowId,$updateCondition)
{
// Get PDO handle
$PDO = new SQL();
$dbh = $PDO->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);
// Build query
$this->sql = 'UPDATE '.$tableName.' SET ';
$fieldCount = count($fieldArray);
for ($i = 0; $i < $fieldCount; $i++){
// If the index is at the last field...
$lastRow = $fieldCount - 1;
if ($i != $lastRow) {
// Add a comma
$this->sql .= $fieldArray[$i].'=:'.$fieldArray[$i].', ';
} else {
// Dont add a comma
$this->sql .= $fieldArray[$i].'=:'.$fieldArray[$i].' ';
}
}
// If row id is null (if we don't know the row id)...
if ($rowId == null || $rowId == "null") {
// Then use the update condition in it's place
$this->sql .= 'WHERE '.$updateCondition.' ';
} else {
// Use the ID
$this->sql .= 'WHERE Id = '.$rowId.' ';
}
try {
// Query
$stmt = $dbh->prepare($this->sql);
// Bind parameters
for ($i = 0; $i < $fieldCount; $i++){
$stmt->bindParam(':'.$fieldArray[$i].'', $fieldValues[$i]);
}
$stmt->execute();
$count = $stmt->rowCount();
echo $count.' row(s) affected by SQL: '.$stmt->queryString;
$stmt->closeCursor();
}
catch (PDOException $pe) {
echo 'Error: ' .$pe->getMessage(). 'SQL: '.$stmt->queryString;
die();
}
// Close connection
$dbh = null;
}
这是我努力编写代码的部分,如果你查看我用于更新脚本的代码..我基本上需要一些类似于我的'add'脚本的东西。
任何帮助都将不胜感激!!
答案 0 :(得分:1)
欢迎使用PHP!这真是一种很棒的语言:))
试试这个:
<?php
public function insert($tableName,$fieldArray,$fieldValues)
{
$sql = "INSERT INTO " . $tableName . " (".implode(',', $fieldArray).") VALUES (".implode(',', $fieldValues).")";
// TODO: Execute $sql query
}
答案 1 :(得分:0)
您基本上应该写出您的函数,然后在最后打印出它创建的结果SQL语句。一旦您能够从该级别查看它们,您可以在查询浏览器中尝试它们,看看您是否正确构建它们。