How to extract the value of a select within select using php? - php

I have this code here:
if(isset($_POST['possible_new_dd'])){
$dd = $_POST['possible_new_dd'];
$id = $_POST['possible_new_dd_id'];
$sql = mysqli_query($connection, "SELECT SUM(COILS),MACHINE, (SELECT COILS FROM ORDERS WHERE ID='$id') FROM ORDERS WHERE MACHINE=(SELECT MACHINE FROM ORDERS WHERE ID='$id') AND C_DD='$dd';");
$row = mysqli_fetch_array($sql);
$json->coils = $row['SUM(COILS)'];
$json->machine = $row['MACHINE'];
$json->new_coil = $row['?THE SELECT QUERY?'];
$j = json_encode($json);
echo$j;
}
In the json string I can read machine and coils, but I cant find a way to read this bit (SELECT COILS FROM ORDERS WHERE ID='$id').
How do I get this value to be stored into a json string?
Thanks

The simplest way is use an alias eg MY_COL
$sql = mysqli_query($connection, "SELECT SUM(COILS),MACHINE,
(SELECT COILS FROM ORDERS WHERE ID='$id') AS MY_COL
FROM ORDERS
WHERE MACHINE=(SELECT MACHINE FROM ORDERS WHERE ID='$id') AND C_DD='$dd';");
and so you can access easly to the result
$json->my_col= $row['MY_COL'];
but you should not use php var inside in SQL. (you are at risk for sql injection ) To avoid this you should use binding param so take a look at this feature and refactor your code

Related

Php loop all result in next mysql query

i have a small problem. I use two mysql queries for getting data.
First i want to get IDs from groups
$sqlGoups = "SELECT * from `groups` WHERE `Date`='$TodayDate' ";
$result = $conn->query($sqlGoups);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$IDgroups = $row["ID"];
With that, I'll get those IDs, for example 5, 7, 12, 15, 22
I want to put them all in the next mysql query:
$sqlNext = "SELECT * FROM `orders` WHERE ID = '$IDgroups' ORDER BY `ID` ASC ";
$result = $conn->query($sqlNext);
When I do this, I get the result only for the first ID (5). And I want for each
I can not INNER JOIN tables because I use this in next query.
I tried with foreach loop, but no effect.
Try this code
SELECT * FROM `orders`
WHERE ID REGEXP CONCAT('(^|,)(', REPLACE('$IDgroups', ',', '|'), ')(,|$)')
ORDER BY `ID` ASC
Just like #Elanochecer commented the best bet should be a JOIN statement, but if you wish to go through your route, you could use the IN and provide the IDs as comma separated string, your query should look similar to the one below:
...
$sqlNext = "SELECT * FROM orders WHERE ID IN ('$IDgroups') ORDER BY ID ASC ";
...
Also, confirm if $IDgroups is in the format 1,2,3,4
If you provide the schema I could come up with a workable JOIN statement for you, preferably you can create a repo with the schema

Declare $row for two tables

I want to echo data from two tables to one variable. Here is the code that I have so far:
$sqlCommand = "SELECT * FROM News ORDER BY id DESC LIMIT 10";
$sqlCommand3 = "SELECT * FROM Users ORDER BY id";
$query = mysql_query($sqlCommand) or die(mysql_error());
$query3 = mysql_query($sqlCommand3) or die(mysql_error());
$count = mysql_num_rows($query);
if($count > 1) {
$News .= "";
// How do I add the query3 here?? along side the already existing one
while($row = mysql_fetch_array($query)) {
// some of the $row here are from query one and some are from query 3
$News .= "<div class=\"news-post\"> <img src=\"".$row['author']."\"><p>".$row['author']."</p> <h2>".$row['title']."</h2></div>";
} // close while
This isn't the right way to go about it, instead try using a SQL join. In this case, you'll want a unique FULL OUTER JOIN.
SELECT * FROM News
FULL OUTER JOIN USERS
ON News.id = Users.id
WHERE News.id IS NULL
OR Users.id IS NULL;
This should give you all rows containing all columns from both tables. Depending on the actual relationship, you may want some different kind of join (refer to previous link)..but this seems like what you were trying to accomplish in your example.
Warning: you are using the mysql_* extension which has been deprecated in PHP 5.5. Please use either mysqli_* or PDO.
Your User table should be linked to the News table by a oneToMany association.
So a user writes a news and a new is written by a user.
And you need to add a join in your SQL query.
$sql = 'SELECT u.username, n.* FROM News n JOIN User u ON n.user_id = u.id';
Then, you while only have to execute one SQL statement and display the result in you HTML.
Have look to this website.

Getting ID of Variable in database

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.

PHP SQLSRV Sorting with Parameter of Prepared Statement

I can't figure out why sorting will work as long as I'm not using $sort as a passed in parameter. Example below will work for sorting:
$sort = "quantity desc";
$sql = " with items as (
SELECT i.[item_id]
,i.[name]
,i.[value]
,i.[quantity]
,i.[available]
,isnull(r.awarded, 0) as awarded
, ROW_NUMBER() OVER(
ORDER BY $sort
) rowNumber
FROM [Intranet].[dbo].[Goodwell_Item] i
LEFT JOIN (
SELECT r.item_id
, COUNT(1) awarded
from [Intranet].[dbo].[Goodwell_Reward] r
group by r.item_id
) as r
ON i.item_id = r.item_id
)
SELECT *
FROM items
WHERE rowNumber BETWEEN (?) and (?)
and ( (?) = '' OR (available = (?)))
";
$params = array( $pagify['startFrom'], $end, $available, $available );
$stmt = sqlsrv_query( $conn, $sql, $params );
However if I change the line with ORDER BY to:
ORDER BY (?)
and add it to my $params like so:
$params = array($sort, $pagify['startFrom'], $end, $available, $available );
then the sort for some reason is being ignored.
Please tell me how to get the sort working in a way that doesn't allow SQL injection.
I am dealing with this exact issue right now, and cannot find anything online to help.
I have tried:
$query = "SELECT * FROM {$this->view} WHERE SeriesID = ? ORDER BY ? ";
$result = $conn->getData($query, array($seriesID,$sortBy));
and
$query = "SELECT * FROM {$this->view} WHERE SeriesID = ? ORDER BY ? ?";
$result = $conn->getData($query, array($seriesID,$sortBy,$sortOrder));
In both cases, I get no error, and no results.
I think the only way to solve this safely is to use a switch statement before the query to manually validate the acceptable values. However, unless you're only ever dealing with one table, you can't know what the possible values are for the SortBy column.
However, if you just go with the assumption that the values at this point have already been cleaned, you can go with the non-parameterized version like this:
$query = "SELECT * FROM {$this->view} WHERE SeriesID = ? ORDER BY " . $sortBy . " " . $sortOrder;
$result = $conn->getData($query, array($seriesID));
What I plan to do is make sure to validate sortBy and sortOrder before I pass them to the method that contains this code. By doing it this way, each place I call the code becomes responsible for validating the data before sending it. The calling code would know the valid possible values for the table (or view in this case) that it is calling. (I'm the author of both pieces of code in this case, so I know it's safe.)
So, in short, just make sure that the values at this point in the code are already cleaned and safe, and push that responsibility up one level the code that calls this code.

mysql nested subqueries with php

I have two tables. I want to be able to get the orders of each id in the credit table from the orders table code below:
$downlinequery = "SELECT recid, Level, sp1 FROM credit
WHERE sp1 = '$id' or sp2 = '$id' or sp3 = '$id' or sp4 = '$id'
or sp5 = '$id' or sp6 = '$id' or sp7 = '$id' or sp8 = '$id'" ;
$downlineresult = mysql_query($downlinequery) ;
while ($downlinerow = mysql_fetch_array($downlineresult)) {
extract($downlinerow) ;
$orderquery = "SELECT date,cc,cop FROM order WHERE userid='1127'" ;
$orderresult = mysql_query($orderquery) or die("unable to get orders");
while($orderrow = mysql_fetch_array($orderresult)){
extract($orderrow);
echo "$date,$cc,$cop" ;
}
}
but i keep getting the error: unable to get orders
Is it possible to make queries while another is running ?
The error might happend because "ORDER" is a reserved word in MySQL. You should escape it with backticks:
$orderquery = "SELECT date,cc,cop FROM `order` WHERE userid=1127" ;
Same should be for "date", although that's being tolerated (see further down in the same page I linked)
As for your question, of course you can do queries in a loop (although that's not really the best in terms of performance). But if your tables have a foreing key (I'm guessing 'recid' and 'userid') you can build a JOINed query instead
To your actual question:
I don't think the question is right. The first query is not running. It ran and it filled result in $downlineresult (mysql_query) and then, you are just iterating thru the parts of the result (mysql_fetch_array).
It seems you have error in your MySQL query, so you should use:
echo mysql_error();
See the description of the methods you use:
mysql_query
mysql_fetch_array

Categories