2016-01-28 53 views
1

我只是用數字更新數據庫,但我只希望數字的最後一位數字實際更新。我不確定是否在PHP或MySql中執行此操作。更新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 & A_Team: 34

我只想要最後一位數字實際進入sql字符串的更新,因此在數據庫中它看起來像這樣:

N_Team: 1 & A_Team: 4

+1

所以你有效嘗試設置分數['值%10'(http://php.net/manual/en/internals2.opcodes。 mod.php)? –

+0

我不這麼認爲,不。 –

+0

爲什麼不呢?按照你的例子,'21%10 = 1'和'34%10 = 4'。 –

回答

4

嘗試:

$N_Score = substr($_POST['N_Score'], -1); 
$A_Score = substr($_POST['A_Score'], -1); 

這是假定值是非零的長度,你可能需要一些錯誤處理。

您可能還想考慮防範SQL注入。

+0

啊,完美。我知道這很簡單。這只是一個實驗,不是公開的。謝謝! –

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)); 
} 
+0

謝謝。只是接受oroboto的回答,因爲他是第一個。 –

+0

沒關係,很高興幫忙 – Phiter

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> 
相關問題