我的strlen和substr PHP有什么问题


Whats wrong with my with strlen and substr PHP

创建了一个名为product_的会话。当我点击添加到购物车按钮时,我的

$_SESSION['product_' . $_GET['add']]会像这个产品一样吗171是我拥有的产品的id。我打印出我的查询,看看发生了什么,我的item_id不回171这是sendind 17 不是 171 。我试着改变数字,但它不工作。

这是我的代码。

function cart(){
    global $conn;
    foreach ($_SESSION as $name => $value) {
        if($value > 0){
        if(substr($name, 0, 8 ) == "product_"){
            $length = strlen($name -8);
            $item_id = substr($name, 8 , $length);
    $query = "SELECT * FROM gallery2 WHERE id =".escape_string($item_id)."";
    print_r($name); echo' <strong>this is the name</strong></br>';
    print_r($item_id); echo'  <strong>this is the id without the name -product_</strong></br>';...

这就是我得到的

product_171这是名称

17这是没有名称的id -product_为什么我没有拿到完整的身份证?

检查字符串长度的代码段是错误的:

if(substr($name, 0, 8 ) == "product_"){
        $length = strlen($name -8);
        $item_id = substr($name, 8 , $length);
...

您正在检查$name - 8的字符串,并且$name - 8等于-8,它们有2个字符,因此它总是得到2个字符。

-8应该在strlen()功能之外:

if(substr($name, 0, 8 ) == "product_"){
        $length = strlen($name) - 8;
        $item_id = substr($name, 8 , $length);
...

您可以使用explosion来获取id。

foreach ($_SESSION as $name => $value) {
    $data = explode("_", $name);
    $item_id = $data[1];
    ...