how to loop through a set of GET values in php

大城市里の小女人 提交于 2019-12-02 07:44:06

You have semicolons after some values maybe you should pass just the integer this are qoh and qbuys. Apart of that you should use mysql_real_escape_string() and (int) before integer values to prevent SQL injection e.g.:

$int = (int)$_GET['price'];
$string = $_GET['val'];
mysql_real_escape_string($string);

Also if you want to pass multiple values you have to use array for them:

HTML

<input type="hidden" name="ids[]" value="1">
<input type="hidden" name="ids[]" value="2">
<input type="hidden" name="ids[]" value="3">

PHP

$ids = $_GET['ids'];
foreach($ids as $id) {
    $sql = 'UPDATE table SET field=? WHERE id='.(int)$id;
    ....
}

Either convert the parameters to array parameters (e.g. qoh[]) and then iterate in parallel, or parse the query string manually.

You can use the $_SERVER['QUERY_STRING'] with foreach loop like this:

foreach($_SERVER['QUERY_STRING'] as $key => $value){
  echo "$key - $value <br />";
}

This way you can get the values of GET and use in your database query in similar fashion using foreach loop.

I assume that PID in prod_table is of integer type. Doesn't $id variable contain "2;" instead of 2? Anyway, what kind of error do you get?

Have your url like http://localhost/pos/php/checkout.php?ids[]=2&qoh[]=12&qbuys[]=&ids[]=6&qoh[]=2304&qbuys[]=304&ids[]=4&qoh[]=699&qbuys[]=99... using a HTML structure like infinity pointed out.

Then:

foreach ($_GET['ids'] as $k => $v) {
    $id = (int)$v;
    $qtyhnd = (int)$_GET['qoh'][$k];
    $qtytbuy = (int)$_GET['qbuys'][$k];
    $left = $qtyhnd - $qtytbuy;

    if ($qtyhnd >= $qtytbuy) {
        $update = query_database(
            "UPDATE prod_table SET QTYHAND='$left' WHERE PID='$id'",
            "onstor",
            $link);
    }
}

And if the database type of QTYHAND and PID are int, exclude single quotes (') from your SQL queries.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!