我在数据库中插入名称,号码和公司。
我的表格很简单:
id(primary key)
name
slideView
company
如果传递给它的名称存在,我需要更新此信息,如果没有创建包含此数据的新行。我看过REPLACE INTO
,但我不认为这对我有用......因为我根本不接触ID。
我的代码是:
insertData($name,$count,$company);
function insertData($name, $count, $company) {
#Try/Catch statement to connect to DB, and insert data
try {
#DB username/password
$usernameDB = '****';
$passwordDB = '****';
#Create new PHP Database Object with the address, username, and password as parameters
$pdo = new PDO('mysql:host=localhost;dbname=*****', $usernameDB, $passwordDB);
#Set pdo attributes to handle errors
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
#assign the sth variable (sth means statement handle) to insert the data
$sth = $pdo->prepare("REPLACE INTO ***** SET name = ?, slideView = ?, company = ?");
#Execute the insert
$sth->execute(array($name,$count,$company));
#Error if can't connect or insert
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}#/try
}
我是SQL的新手,并且havnt找到了一个很好的方法来实现这一目标。
答案 0 :(得分:4)
你可能更好地使用insert ... on duplicate update
语法,虽然这意味着传递一些额外的参数,但它可以消除某些似乎不断出现的problems in the replace into语法。
REPLACE INTO ***** SET name = ?, slideView = ?, company = ?
可以写成:
insert into yourTableName (name, slideView, company)
values (:name, :slideView, :company)
on duplicate key update set
slideView=:$slideView2, company=:company2
然后执行就像这样:
$sth->execute(array(':name' => $name, ':slideView' => $count,
':company' => $company, ':slideView2' => $count, ':company2' => $company));
上面的格式使用命名参数(它们更容易读取/调试)并将新行插入数据库 - 或者如果唯一/主键列name
已经具有该值,则用剩余的信息更新行。
你必须在这里使用两次参数(即使slideView和公司将包含相同的信息),因为在查询中不能使用两次参数。
答案 1 :(得分:2)
REPLACE INTO应该可以正常工作 - 它还会检查具有UNIQUE约束的列。因此,您只需要mark your name
column as unique,以便REPLACE INTO将其识别为重复。
我没有尝试过这个特殊用例,但文档似乎允许它。