Calling a PHP Function into sql query - php

I have a MySQL table called "invoice_prod" :
id | qte | price | id_tva
And another table called "tva" :
id_tva | content
Now, I want to find the total of an invoice, so I made this query and it works.
$sql_mnt = mysql_query("
SELECT SUM( (qte * price) * ( 1 + (tva / 100))) AS total_un_prod
FROM invoice_prod
WHERE id='$id_invoice'
");
I have just one problem with this query. The "tva" return the "id of the tva" and not its content. Which I have to extract its content from the table "tva".
Clearly, this query return this value of the tva : "1", or, it should return "18%" which is the content of the tva's ID.
I tried to make a PHP function that extracts the tva's content from an id and include it into the SQL query like this :
$sql_mnt = mysql_query("
SELECT SUM(( qte * price) * ( 1 + (" .
tva_get_by_id(tva) . "/ 100))) AS total_un_prod
FROM invoice_prod
WHRE id='$id_invoice'
");
But it doesn't work.
What should I do ?
Thanks a lot for your help and have a nice day :)

use
$sql_mnt = mysql_query("
SELECT SUM((`qte`*`price`)*(1+(`content`/100))) AS `total_un_prod`
FROM `invoice_prod`
LEFT JOIN `tva` USING (`id_tva`)
WHERE `id`='".mysql_real_escape_string($id_invoice)."'");
this connects the two tables within mysql, so you can use the content field directly, which I presume holds the TVA percentage.
edit formatted and addressed the escaping of id_invoice as well (I guess it is int so a cast would suffice, but if not, this will work as well)

I am not sure I understand correctly what you're doing here, but it looks like what you want is an INNER JOIN on the tva table, and then use tva.content in your calculation. Is that correct?

Related

Getting Empty array on INNER query in MySQL

I am a newbie in PHP/MySQL and this is my first question on stackoverflow, so please ignore any mistake if I have made any.
I am trying to get records from a table through this query.
$CId = $this->input->post('Child_id'); //child_id is the value from a textfield
$r_detail = ("SELECT *
FROM `result_details`
WHERE ResultId
IN (SELECT Result_Id
FROM `results`
WHERE childId = '".$CId." ') " );
this query is returning an empty $r_detail. However when I query the same statement in PHPMyAdmin in localhost and change "$CID" to a number, I get the desired records.
Any Help will be much appreciated.
You have a space in INNER JOIN WHERE: '".$CId." ' should be '".$CId."'.
$r_detail = ("SELECT *
FROM `result_details`
WHERE ResultId
IN (SELECT Result_Id
FROM `results`
WHERE childId = '".$CId." ') " );
has just string...you need to call some db function to get the data such as in code igniter may be
$this->db->query($r_detail);

Multiple Select Query MySQL without while loop

I have two different tables where I need to fetch the list of store ids from one table and then find the list of coupons for those store ids.
Currently,
SELECT `storename` FROM `stores` where `brandname` = 21
This will return something like
Store 1
Store 2
Store 3
Store 4
And I need to to run another query like
SELECT * FROM `coupons` where `storename` = {{All these stores}}
I can't use while loops because, the number of stores comes from first query can't be determined and the the output I want was not coming as expected while using while loop as I am trying to do something like
while(first query output get storename)
{
do query here
while(second query output get all coupons per store)
{
// All coupons display here.
}
}
This is making quite complicated as well, is there anyway that I can tweak my SQL query and get results easily?
Thanks
you can use this query:
SELECT * FROM `coupons`
where `storename` IN (
SELECT `storename` FROM `stores` where `brandname` = 21);
$query = 'SELECT t.storename, h.couponid AS couponsid, h.coupon AS couponvalue'
. ' FROM #__stores AS t'
. ' LEFT JOIN #__coupons AS h ON h.storename = t.storename'
. ' where `brandname` = 21'
. ' ORDER BY anything you like'
;

How to count if value of a variable is repeated?

I am learning how to work with MySQL, and at the moment I succeed to show data from my table, using:
while($objResult2 = mysqli_fetch_assoc($objQuery_product)) {
Results are shown by using this variable $objResult2["id_product"]; this way i can take from DB any field I want like: $objResult2["name"]; $objResult2["email"]; etc.
But what i do if i have in the table more rows with the same id_product?
I want to write a if statment, which counts if id_product repeats. How to do that? If it is a lot of work, atleast please give me an idea of the right tutorial that I must read. Because i am trying second day to fix this, and searched google but i didnt find what i need, or maybe i coulndt understand it....
This is my query
$sql_product = "SELECT * FROM ps_product AS prod";
$join_product = " LEFT JOIN ps_product_lang AS lang ON lang.id_product = prod.id_product";
$join2_product = " LEFT JOIN ps_stock_available AS stok ON stok.id_product = prod.id_product";
$where_product =" WHERE prod.id_category_default = $idp AND lang.id_lang = 8";
$sql_product = $sql_product.$join_product.$join2_product.$where_product;
$objQuery_product = mysqli_query($objConnect, $sql_product) or die ("Error Query [".$sql_product."]");
You can simple remove the same id_product using DISTINCT keyword in your query. Such as:
SELECT DISTINCT id_product FROM my_table
This will give you results with different ids only.
The second way of doing it is taking the output values inside an array.
In your while loop:
$my_array[] = $objResult2["id_product"];
Then using array_filter remove all the duplicates inside the array.
YOu can also use array_count_values() if you want to count the duplicate values.
Ok here we go. For example you are fetching data with this query.
select id_product, name from PRODUCTS;
Suppose above query gives you 5 records.
id_product name
1 bat
2 hockey
2 hockey
3 shoes
4 gloves
Now you got 2,2 and hockey, hockey. Instead of thinking this way that you have to introduce an if statement to filter repeating records or same name or id_product records.
Rewrite your sql query like this.
select distinct id_product, name from PRODUCTS;
Or if you need count of each then my friend you will write your query something like this...
Graham Ritchie, if Andrei needs count of each repeating record then we will do something like this in our query.
SELECT PRODUCT_ID,
COUNT(PRODUCT_ID) AS Num_Of_Occurrences
FROM PRODUCTS
GROUP BY PRODUCT_ID
HAVING ( COUNT(PRODUCT_ID) > 1 );
SELECT id_product,COUNT(*) AS count
FROM tablename
GROUP BY id_product;
This query will then return you two items in your query
$objResult2["id_product"] //and
$objResult2["count"]
The if statement is then just
if($objResult2["count"] > 1){
//Do whatever you want to do with items with more than 1 occurence.
//for this example we will echo out all of the `product_id` that occur more than once.
echo $objResult2["id_product"] . " occurs more than once in the database<br/>";
}

Get Duplicate data from the Database

i want to fetch duplicate data from the database but the problem is:
i have userids in an array like :
1235, 1235, 5468, 84321, 1235
i used implode and to make that array in string in implement into the database like:
"select * from tbl_name where userid in ('" . $implode_arr . "') limit 0, 10";
which is give me the result like 1235, 5468, 84321 but i want all the data, solution for this is simply run the query in the FOR LOOP or else
but i want same because i add the pagination within the query.
I don't want any code because its already working but the problem is to add pagination Please help to resolve the problem :(
It sounds like you want to join in the user data into this query. You can do that using a LEFT JOIN like this:
SELECT *
FROM tbl_name
LEFT JOIN database_name.user ON database_name.user.id = tbl_name.userid
WHERE userid IN (...)
LIMIT 0, 10
This is assuming your users are stored in the user table in the database_name database, and that the user table has an id field which matches up to the tbl_name field userid. If your fields or table names are different, just change them in this query. In PHP that would be:
"SELECT * FROM tbl_name LEFT JOIN database_name.user ON database_name.user.id = tbl_name.userid WHERE userid IN ('" . $implode_arr . "') LIMIT 0, 10"
Note that to connect two databases, both must be accessible by your same connected user.
Try this it would also work as expected
select * from tbl_name where FIND_IN_SET(user_id,'1235, 1235, 5468, 84321, 1235
') limit 1,10
Check this to remove duplicates

Update values of database with values that are already in DB

I've a database that stores data read from different sensors. The table looks like this:
[SensorID][timestampMS][value]
[Sensor1][123420][10]
[Sensor1][123424][15]
[Sensor1][123428][6554]
[Sensor1][123429][20]
What I would like to do is the following: There are some reads that are corrupted (numbers that are 6554), and I would like to Update that with the next value that is not corrupted (in the example shown below that would be 20). So, if a number is 6554, I would like to update that with the next value (in timestamp), that is not corrupted.
I was thinking on doing this in PHP, but I wonder if it's possible to do it directly with a SQL script.
Appreciate :)
You can use a correlated sub-query...
UPDATE
myTable
SET
value = (SELECT value FROM myTable AS NextValue WHERE sensorID = myTable.SensorID AND timestampMS > myTable.timestampMS ORDER BY timestampMS ASC LIMIT 1)
WHERE
value = 6554
The sub-query gets all the following results, ordered by timestampMS and takes just the first one; That being the next value for that SensorID.
Note: If no "next" value exists, it will attempt to update with a value of NULL. To get around this, you can add this to the WHERE clause...
AND EXISTS (SELECT value FROM myTable AS NextValue WHERE sensorID = myTable.SensorID AND timestampMS > myTable.timestampMS ORDER BY timestampMS ASC LIMIT 1)
EDIT
Or, to be shorter, just use IFNULL(<sub_query>, value)...
Not sure if this is valid syntax, can't test it ATM. You may need to change this to be JOINs instead of the nested subqueries, but in concept you can do something like (for SQL Server):
UPDATE t1
SET Value = ( SELECT Value
from MyTable t2
WHERE t2.SensorID =t1.SensorID
AND t2.[timestamp] =
( SELECT MIN([TimeStamp])
FROM mytable t3
where t3.sensorid = t2.sensorID
AND t3.[timestamp] > t2.[timestamp]
)
)
FROM Mytable t1
WHERE t1.value = 6554
I did a workaround based on Dems solution, and it works in Mysql:
I've created a "copy" of the sensors table like this:
drop table if exists sensors_new;
create table if not exists sensors_new like sensors;
insert into sensors_new select * from sensors;
Then I do what Dems recommended me doing, but using this new aux table in the select (to avoid the error that Mysql launches when Updating a table while doing a select in the same table).
UPDATE
sensors
SET
raw_data = (SELECT raw_data FROM sensors_new AS NextValue WHERE sensor_id = sensors.sensor_id AND timestampMS > sensors.timestampMS ORDER BY timestampMS ASC LIMIT 1)
WHERE
value = 6554
Then, just drop this auxiliar table.
I hope this helps Mysql users.

Categories