我将arraylist从android发送到php。我想取代旧的男人气球作为新的男人气球。在我的表中包含两列1.menuimage 2.menuname ..我想只更新新的menunames
我的表格结构
test(table name)
menucode menuimage menuname
1 image p
2 " q
3 " r
4 " s
5 " t
我想根据菜单代码仅更新menuname ...我正在传递菜单代码[1,2,3,4,5,6,7] ......
<?php
$old_menu_code = explode(",", str_replace(array("[","]"), "", $_POST['menucode']));
$new_menu_names = explode(",", str_replace(array("[","]"), "", $_POST['editmainmenu']));
mysql_connect("localhost", "root", "root");
mysql_select_db("test");
foreach ($old_menu_names as $key => $old_name) {
$new_name = mysql_real_escape_string($new_menu_names[$key]);
$old_code = mysql_real_escape_string($old_menu_code[$key]);
mysql_query("UPDATE `test` SET `menuname` = '$new_name' WHERE menucode= '$old_code'") or die('Error' . mysql_error());
echo "Updated";
}
?>
上面的代码测试是数据库包含测试表。在测试表中包含两列一个menuimage和menuname。在menuimage中包含7个图像,menuname包含7个menunmaes。我只想更新menuinames。但上面的代码只更新第一行menunames列。剩下的行没有更新..请问我做了什么错误
答案 0 :(得分:0)
您可以使用str_replace
&amp; explode
实现你想要的......
吐痰数据
$old_menu_names = "[p,q,r,s,t,u]" ; // or $old_menu_names = $_POST['menuname'] ;
$new_menu_names = "[a,b,c,d,e,f]" ; // or $new_menu_names = $_POST['editmainmenu'] ;
$old_menu_names = explode(",", str_replace(array("[","]"), "", $old_menu_names));
$new_menu_names = explode(",", str_replace(array("[","]"), "", $new_menu_names));
SQL错误
mysql_query("UPDATE `test` SET `menuname` = '$new_name' WHERE menuname = '$old_name'")
由于您尝试更新条件menuname
WHERE menuname =
,因此哪些陈述不起作用
我建议您将其更改为memuid
,如果它存在于您的表格中或首先获取ID
并使用它来更新它。
编辑1
更新代码
$mysql = new mysqli("localhost","root","root","test");
$sql = "SELECT menucode FROM test where menuname = '%s' ";
foreach ($old_menu_names as $key => $old_name) {
$new_name = mysql_real_escape_string($new_menu_names[$key]);
$old_code = mysql_real_escape_string($old_menu_names[$key]);
$result = $mysql->query(sprintf($sql,$old_code))->fetch_assoc();
if(!empty($result['menucode']))
{
$mysql->query(sprintf("UPDATE `test` SET `menuname` = '%s' WHERE menucode= '%d'",$new_name,$result['menucode']));
echo "Updated " , $mysql->affected_rows . PHP_EOL;
}
else
{
echo "Missing menucode for $old_code " , PHP_EOL;
}
}
我希望这会有所帮助