Jump to content

Grabbing IDs from Database


9three

Recommended Posts

Hey

 

I'm creating a simple shopping cart but I'm stuck trying to figure out why I'm not getting the output I'm looking for.

 

function product_exists($input_id)
{
  $mysqli = new mysqli('localhost', 'root', '', 'store');
  $result = $mysqli->query("SELECT ID FROM products");
  
  $array = array();
  while ($row = $result->fetch_object())
  {
    $array[] = $row->ID;
  }
  
  foreach ($array as $product_id)
  {
    if ($product_id == $input_id)
      return true;
    else
      return false;
  }
}

 

Basically what I'm trying to do is store all the IDs that are in my database into an array and compare the ID the user has given me. If it matches it needs to return true, else false.

 

Here is the front side:

 

$product_id = $_REQUEST['id'];
if (product_exists($product_id))
  echo 'Product Exist!';
else
  echo 'Not working yet';

 

It's echoing out Not working yet

 

Can anyone lend a hand please?

Link to comment
https://forums.phpfreaks.com/topic/162854-grabbing-ids-from-database/
Share on other sites

That's because you are returning on the first false.

 

However, one of the great points of using a database is to only select the data you are interested in. You should have a WHERE clause on your query that finds a row that matches your $input_id and then just check if a row was returned.

 

Querying for all the rows and looping through them looking for a match will take up an increasing amount of memory and an increasing amount of time as the number of products in the table increases.

Got it. Thank you.

 

$result = $mysqli->query("SELECT ID FROM products WHERE ID = '$input_id'");

 

I'm trying to re factor the loops because if I (for example)4,000 items then the function would need to place all those IDs into an array and then sort through it. I would imagine it would slow down the application a lot.

I tried doing this

 

$mysqli = new mysqli('localhost', 'root', '', 'store');
  $result = $mysqli->query("SELECT ID FROM products WHERE ID = '$input_id'");
  
  if ($result == $input_id)
    return true;
  return false;

 

But the same issue raises up again. id 1 works, but anything higher returns false.

Return Values

For SELECT, SHOW, DESCRIBE or EXPLAIN mysqli_query() will return a result object.

 

$mysqli->query() returns a result object, you would need to access the ->num_rows property to determine if there is a matching row.

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.