doufu1950 2016-09-20 14:17
浏览 20
已采纳

我的strlen和substr PHP有什么问题

I created a session called product_ . When i click in my add to cart button, my

$_SESSION['product_' . $_GET['add']] will be like this product_171 the 171 is the id from a product that i have. I printed out my query to see what's going on and my item_id is not echoing 171 it's sendind 17 not 171. i tryed to change the numbers but it didn't work.

this is my code.

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>';...

this is what i'm getting

product_171 this is the name

17 this is the id without the name -product_ why im not getting my full id?

  • 写回答

2条回答 默认 最新

  • duanmu6231 2016-09-20 14:26
    关注

    The piece of code where you check the string length is wrong:

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

    You are checking strlen of $name - 8, and $name - 8 is equal to -8, that have 2 characters, so it will always get 2 characters.

    The -8 should be out of the strlen() function:

    if(substr($name, 0, 8 ) == "product_"){
            $length = strlen($name) - 8;
            $item_id = substr($name, 8 , $length);
    ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号