我對PHP很陌生,需要幫助編寫我的網站的添加腳本。我編碼刪除和更新方面,他們正在完美工作。基本上,在我的網站的部分,你可以添加值到幾個文本框,我想要的是,當你點擊'添加'這將添加細節從文本框到數據庫。爲此,我使用PHP,Jquery和Ajax。PHP - 添加腳本
這是我對更新腳本代碼:
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;
}
這是我努力的代碼的一部分,如果你看一下代碼,我用我的更新腳本..我基本上需要類似於我的'添加'腳本的東西。
任何幫助將不勝感激!
你會從看[視頻](http://www.youtube.com/watch?v=RlfLCWKxHJ0)受益..和其他人則來自「Clean Code Talks」系列。 – 2012-03-13 23:22:37