我只是用数字更新数据库,但我只希望数字的最后一位数实际更新。我不确定是在PHP还是MySql中执行此操作。
代码:(未发布完整代码,但相关)
if(isset($_POST['update'])) {
$N_Score = $_POST['N_Score'];
$A_Score = $_POST['A_Score'];
$sql = "UPDATE scores SET N_Score = $N_Score, A_Score = $A_Score";
mysql_query($sql) or die(mysql_error());
<form method = "post" action = "<?php $_PHP_SELF ?>">
<table width = "400" border =" 0" cellspacing = "1" cellpadding = "2">
<tr>
<td width = "10"><?php echo $N_Team; ?> Score:</td>
<td><input name = "N_Score" type = "text" id = "N_Score" value="<?php echo $N_Score; ?>"></td>
</tr>
<tr>
<td width = "10"><?php echo $A_Team; ?> Score:</td>
<td><input name = "A_Score" type = "text" id = "A_Score" value="<?php echo $A_Score; ?>"></td>
</tr>
因此,在表单中,我输入N_Team
和A_Team
的分数,如下所示:
N_Team: 21
&amp; A_Team: 34
我只希望最后一个数字真正进入sql字符串的更新,所以在数据库中它看起来像这样:
N_Team: 1
&amp; A_Team: 4
答案 0 :(得分:4)
尝试:
$N_Score = substr($_POST['N_Score'], -1);
$A_Score = substr($_POST['A_Score'], -1);
这假定值的长度非零,您可能需要一些错误处理。
您可能还想考虑保护自己免受SQL注入。
答案 1 :(得分:2)
这将返回字符串的最后一个字符。
$N_Score = substr($_POST['N_Score'], -1);
$A_Score = substr($_POST['A_Score'], -1);
也许您可以通过转义用户输入来保护系统的完整性:
$N_Score = mysql_real_escape_string(substr($_POST['N_Score'], -1));
$A_Score = mysql_real_escape_string(substr($_POST['A_Score'], -1));
您也可能希望从mysql_*
切换到mysqli_*
,这已经过改进,可以更好地使用。
请记住,如果字符串的大小为0,则代码将为“位置-1处的无值”或其他内容引发错误。
因此,在添加到数据库之前,最好检查字符串是否包含某些内容。
类似的东西:
if ($_POST['N_Score'] != "" and $_POST['A_Score'] != "")
{
$N_Score = mysql_real_escape_string(substr($_POST['N_Score'], -1));
$A_Score = mysql_real_escape_string(substr($_POST['A_Score'], -1));
}
答案 2 :(得分:2)
if(isset($_POST['update'])) {
$N_Score = substr($_POST['N_Score'], -1);
$A_Score = substr($_POST['A_Score'], -1);
$sql = "UPDATE scores SET N_Score = $N_Score, A_Score = $A_Score";
mysql_query($sql) or die(mysql_error());
<form method = "post" action = "<?php $_PHP_SELF ?>">
<table width = "400" border =" 0" cellspacing = "1" cellpadding = "2">
<tr>
<td width = "10"><?php echo $N_Team; ?> Score:</td>
<td><input name = "N_Score" type = "text" id = "N_Score" value="<?php echo $N_Score; ?>"></td>
</tr>
<tr>
<td width = "10"><?php echo $A_Team; ?> Score:</td>
<td><input name = "A_Score" type = "text" id = "A_Score" value="<?php echo $A_Score; ?>"></td>
</tr>