James Allan James Allan - 2 months ago 8
PHP Question

Whats wrong with my with strlen and 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?

Answer

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