gpt4 book ai didi

php - 从表单更新 sql 表中的数据 - 数据必须是唯一的

转载 作者:行者123 更新时间:2023-11-29 00:21:25 25 4
gpt4 key购买 nike

到目前为止,我只学习了 php 和 sql 的基础知识,需要一些指导。我有以下代码来更新 sql 表中的一行数据 - 工作正常:

<?php

$hostname = "localhost";//host name
$dbname = "dpuqsevb_tnysx";//database name
$username = "dpuqsevb_user";//username you use to login to php my admin
$password = "password";//password you use to login

//CONNECTION OBJECT
//This Keeps the Connection to the Databade
$conn = new MySQLi($hostname, $username, $password, $dbname) or die('Can not connect to database')
?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
</head>
<body>

<?php
if(isset($_POST['Submit'])){//if the submit button is clicked

$url_code = $_POST['url_code'];

$update = "UPDATE url_urls SET url_code='$url_code' WHERE id = 7";

$conn->query($update) or die("Cannot update");//update or error

}

?>

<?php

//Create a query

$sql = "SELECT * FROM url_urls WHERE id = 7";

//submit the query and capture the result

$result = $conn->query($sql) or die(mysql_error());

$query=getenv(QUERY_STRING);

parse_str($query);

?>

<form action="" method="post">

<?php

while ($row = $result->fetch_assoc()) {?>

<table border="0" cellspacing="10">

<tr>

<td><input type="text" name="url_code" value="<?php echo $row['url_code']; ?>"></td>

</tr>

<tr>

<td><INPUT TYPE="Submit" VALUE="Update the Record" NAME="Submit"></td>

</tr>

</table>

<?php }
?>

</form>

<?php
if($update){//if the update worked

echo "<b>Update successful!</b>";

}
?>

但是我希望脚本检查其他行,因此没有重复的 $url_code - 换句话说 $url_code 必须是唯一的。

最佳答案

最简单的解决方案是将列 url_code 定义为 UNIQUE在你的数据库中。

现在,一旦您尝试在 url_code 已存在于数据库中的位置插入一个值,您的查询就会失败。这也可以通过 PHP 完成,但我真的建议使用 SQL 解决方案 - 您的数据库已针对此类工作进行了优化。

关于php - 从表单更新 sql 表中的数据 - 数据必须是唯一的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20915921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com