Getting ID of Variable in database - php

I would like to get the id of an item in the database, set it to a variable, and use it. I'm quite new to all this coding stuff. I'm basing this on.
http://jameshamilton.eu/content/simple-php-shopping-cart-tutorial?PHPSESSID=99d373741727e3010a32319f1ebed001
cart.php?action=add&pdin=fbs
$product = $_GET[pdin];
I can't use an integer for 'pdin' so, id like to use its corresponding id which is an integer and plug it into this line of code which only takes integers?
$sql = sprintf("SELECT * FROM products WHERE pdin = %d;", $product);
so in i would take $product = 'pdin' find it's id $id = 'id' and plug it in to the above code
$sql = sprintf("SELECT * FROM products WHERE id = %d;", $id);
I tried reading up on this sql FROM SELECT WHERE... confused me some

I'd use a prepared statement which would also make yourself a bit safer from SQL injection. What database interface are you using from php to mysql?
Here's one option:
$product = $_GET['pdin'];
$stmt = $db->Prepare("select * from products where pdin = ?");
$res = $db->GetAssoc($stmt,$product);

btw,
if you acces array items via key, always use quotations (' or ") otherwise PHP (unnecessary) first check, if key is constant

Ok, I figured it out. I'm sorry i didn't explain it all that well last night. I have a limited brain battery per day, and last night it was depleted.
What i wanted was quite simple. I wanted to find an items associated id in the database.
$query = "SELECT * FROM products WHERE pdin = '$product'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
$productID = $row['id'];
}
Now that parts done and returns the correct id. And the 'item exists' function fires correctly.
//function to check if a product exists
function productExists($productID) {
//use sprintf to make sure that $productID is inserted into the query as a number - to prevent SQL injection
$sql = sprintf("SELECT * FROM products WHERE id = %d;", $productID);
return mysql_num_rows(mysql_query($sql)) > 0;
}
So, Mark and Michal Hatak; When you where talking about using quotations on keys, does that mean...
$sql = sprintf("SELECT * FROM products WHERE 'id' = %d;", $productID);
putting quotations around things like 'id'? And it's for security?
Forgive me, I'm a new graphic designer and not adept at code.

Related

PHP MySQLi query not returning value

I've tried to get this to work in several ways, but I can't get this query to return the Cost value from the database to the $cost variable:
$query2 = "SELECT Cost FROM 'item' WHERE Item = '$item'";
$cost= $db->query($query2);
It seems to be empty when I try to echo it.
(The $item variable is selected from a dropdown list generated from the item-table in the mySQL-db. This works fine and if I echo the value from $item, it returns the name of the item as expected.)
Anybody sees what I'm doing wrong?
I could post my complete code if necessary, but I believe this explanation may be sufficient.
You have to declared 'fetch_array' and Make reference this URL : http://php.net/manual/en/mysqli-result.fetch-array.php
For Example:-
$query = "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result = $mysqli->query($query);
$row = $result->fetch_array(MYSQLI_NUM);
Change $query2 = "SELECT Cost FROM 'item' WHERE Item = '$item'"; to
$query2 = "SELECT Cost FROM item WHERE item = '".$item."'";
Assuming Cost is your column name, the first item is your table name, the second item is another column name (Please change your naming convention and not use the same name for table and column). To make your question clearer, please provide us with your table name, your column names so that we can give you a more accurate answer.
Also you will need to escape your $item variable by using '".$item."' so that you can query from your database proper using that variable.
You will then need to fetch the results from querying the database.
$results = $db->fetch_all($cost);
To test that the data were successfully fetched, you can test it by printing it using print_r($results); This should return you an array of the results.
This might help you.
$input = "100";
$query = "select sal from sal where sal='$input'";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
//This will print sal
echo $row['sal'];
Please let me know if you've any questions.
$query=mysql_query("SELECT Cost FROM item WHERE Item = '$item'");
while($x=mysql_fetch_array($query))
{
$cost=$x['Cost'];
echo $cost; //here we can return the result
}

Opencart Tracking

im trying to display a tracking number for a product on opencart.
so once the order has been placed. i then add a tracking number to it. from which i wish the customer to be able to see on the order history.
// get tracking details
$sql = 'SELECT * FROM '.DB_PREFIX.'order_history'.`tracking_number`;
$query = $this->db->query($sql);
$rates = array();
foreach($query->rows as $result){
$rates[] = $result;
}
$this->data['tracking'] = $tracking;
this would also go in order.php
this is what ive written but it dont work, im not expert at php, i dabble in it. hopefully someone can point me in the right direction,
so this code would go into controller/account/order.php
then on the template i assume i can just insert
<?php echo $tracking; ?> to display tracking deteails.
thanks in advance.
Off hand, I can see that this code will result in error, because your quotes/backticks are out of place:
$sql = 'SELECT * FROM '.DB_PREFIX.'order_history'.`tracking_number`;
Should be more along these lines:
$sql = "SELECT `tracking_number` FROM `".DB_PREFIX."order_history`";
And, assuming you're going to want to pull an order-specific tracking #:
$sql = "SELECT `tracking_number`
FROM `".DB_PREFIX."order_history`
WHERE `order_id` = 'MUFFINS'";
Do yourself a favor and use the double quotes when preparing a MySQL query. It's easier to wrap your stuff in single quotes without having to escape.
As for the remainder of the code, these are not rates but tracking numbers. Assumedly, there would be one tracking number to return per order, which you could wrap up into a single line of code like so:
$my_tracking_number = $this->db->query("
SELECT `tracking_number`
FROM `".DB_PREFIX."order_history`
WHERE `order_id` = 'MUFFINS'
")->row['tracking_number'];
if ( !empty($my_tracking_number) {
$this->data['tracking_number'] = $my_tracking_number;
}
However, if you're going to associate more than one tracking number with an order you can either insert a BLOB column in your order_history table and insert/query serialized data, or create a separate table entirely where multiple rows can be associated with a single order ID.

MySql Pages on the Fly

Problem solved
The answer was
$query = "SELECT manager FROM tablename WHERE manager='$manager'";
Subtle difference, but removing the dots before and after $manager was the answer.
Credit to PHPFreaks.com
I had this;
<?php include 'dbdetails.php';
$id = mysql_real_escape_string($_GET['id']);
$query = 'SELECT `column` FROM `tablename` WHERE `id` = '.$id.' ';
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo $row['column'];
?>
(taken from here)
This works fine if I am solely working with an ID, however I have repeated values in the column I need to work with so ID will not work for what I am trying to achieve.
Essentially I am trying to create pages on the fly using the Manager column as the query as opposed to the ID.
What would be the correct way to achieve this? I presume DISTINCT comes into play?
I am aiming for;
Micky Adams
as my structure, where it fetches all instances of Micky Adams or whichever manager name is set up as the anchor.
If you changed it to:
$manager = $_GET['manager'];
$query = 'SELECT `column` FROM `tablename` WHERE `manager` = '.$manager.' ';
Wouldn't that achieve what you want? If you had more than one instance of the manager DISTINCT only partly helps depending how your data is actually stored.

PHP: Where clause will not execute when using a variable

For the user I am testing with, their org_id column value is "student_life"
I am trying to have this function display whatever rows have the student_life column = 1. (so yes there is a column student_life which is a boolean, and then I also have a separate column named org_id and in this case has the value student_life)
I am pretty sure there is a syntax error but I cannot figure it out.
function org_id_users_table()
{
$org_id = mysql_real_escape_string($_POST["org_id"]);
$sql = $this->query("SELECT * FROM ".DBTBLE." WHERE '$org_id' = '1'");
$result = $sql['sql'];
$num_rows = $sql['num_rows'];
$this->create_table($result, $num_rows);
}
(when I replace $org_id in the "$sql=..." line with student_life the code works.
You're quoting the column name, which makes MySQL think it's a string.
$sql = $this->query("SELECT * FROM ".DBTBLE." WHERE $org_id = '1'");
Edit:
Based on your comments, I think what you actually want is this:
$sql = $this->query("SELECT * FROM ".DBTBLE." WHERE org_id = '$org_id'");
Change quotes.
$sql = $this->query("SELECT * FROM ".DBTBLE." WHERE `$org_id` = '1'");
P.S. Why shouldn't I use mysql_* functions in PHP?
Where is this coming from? $_POST["org_id"]
Do you have a form on the page posting that? Or are you just trying to get that from the database? If so, wouldn't you need another query to obtain that first?
$row_MyFirstQuery['org_id']
Otherwise if it is $_POST["org_id"], wouldn't it be single quotes not double? $_POST['org_id']

Stripping a URL of an ID to Query MYSQL database

if i have a category page that im rendering by querying the subcategories in my database, then if i click on one of the subcategories it sends me to
mydomain.com/product_list.php?id=subcategory.
is there a way take the subcategory from the url to query the database to only show the products in that subcategory?
i think it'll look something like:
$sql = mysql_query("SELECT * FROM products");
This can be obtained from $_GET DOCs.
$subcategory_id = $_GET['id'];
So this would become:
if(array_key_exists('id', $_GET) and is_numeric($_GET['id'])) {
$subcategory_id = (int) $_GET['id'];
$SQL = "SELECT * FROM products WHERE subcategory_id = $subcategory_id";
}
Note I have cast the input variable to an integer to prevent SQL injection etc. As the ID must always be a number.
If you need to pass in a string then use mysql_real_escape_string() DOCs on it first and don't type cast to an integer (int):
if(array_key_exists('id', $_GET)) {
$subcategory_id = mysql_real_escape_string($_GET['id']);
$SQL = "SELECT * FROM products WHERE subcategory_id = '$subcategory_id'";
}
$query = mysql_query("SELECT * FROM `products` WHERE `id` = " . mysql_real_escape_string($_GET['id']);
Of course, that's assuming the table name is products, and the ID columns is id.
Your question is a little confusing. I think to start some tutorials on PHP should be looked at, and the different types of http requests.
What you are looking at is called a GET request. You can access all key, value pairs after the ? in a url through the superglobal $_GET this is an associate array containing all key => values.
So as per above $_GET['id'] is the value you want. But please before you begin look at SQL injection, it is too easy to think that that value can be used directly to make a query.

Categories