codeigniter how to manipulate value between tables - php

can some1 help me with manipulating value between two tables?
Example:
table 1:
No. Name Unit
1 snack 10
table 2:
No. name buy
1 emily 5
what im want to do is, if emily bought 5 units then table 1 result should be left 5 units..
unit = unit - buy
----> how to translate this into codeigniter???
if can, give me the link to some tutor about manipulating table value in database...

Simple Update Table1 when some one brought somthing:
Like:
$this->db->update('table1', array('Unit' => 'Unit - ' . (int) $buy, FALSE));
if you want any condition try this:
$this->db->where('id', 1);//static id 1
$this->db->update('table1', array('Unit' => 'Unit - ' . (int) $buy, FALSE));
Note: id is column name of Table1
Note: You need to check Out of Stock Condition also.

EllisLab has a pretty self-explanatory tutorial for using their included database class here. This is how you would load their class:
$this->load->database(); //or changing some specifications in config/autoload.php
This is how you would query and pull the data from the table:
$query = $this->db->query('SELECT unit FROM table1');
$query2 = $this->db->query('SELECT buy FROM table2');
$row= $query->row();
$buy=$row->unit;
$row2= $query->row();
$unit=$row2->buy;
For the actual insertion itself, assuming you've already queried the values of $buy and $unit:
$unit = $unit - $buy;
$sql = "UPDATE table1 SET buy=$unit
WHERE buy=($unit - $buy)";
$this->db->query($sql);

Related

Yii2 query give different result with sql query

"Table1":
id
name
1
Ulrich
2
Stern
"Table2":
id
school
tid
1
A
1
2
B
1
I want to join 2 table to get all information. With SQL query like this:
SELECT Table1.id,
name,
school
FROM `Table1`
INNER JOIN `Table2`
ON Table1.id = Table2.tid
It gives me all information as I expect (I mean 2 rows with name 'Ulrich').
But when I do with Yii2 query:
$query = self::find();
$query -> alias('t1')
-> innerJoin(['t2'=>'Table2'], 't1.id=t2.tid')
$result = NULL;
if($total = $query->count()) {
$result = $query
-> select([t1.*, t2.school])
->asArray()
->all()
;
$result[0]['count'] = $total;
}
it only gives me 1 row with name 'Ulirch'.
Can anyone help me with this problem. Thank you very much.
If you use ActiveRecord::find() method to create query you will get instance of yii\db\ActiveQuery. This is query designed to load ActiveRecord models. Because of that if you do any type of join and your result set contains primary key of your main model (The model which find() method was called to create query) the ActiveQuery will remove any rows it considers duplicate.
The duplicates are recognised based on main model primary key so the rows in resultset will be considered duplicate even if the data from joined table are different. That's exactly what happened in your case.
To avoid that you have to use query builder instead of ActiveQuery.
Your query can look for example like this:
$query = (new \yii\db\Query())
->from(['t1' => self::tableName()])
->innerJoin(['t2'=>'Table2'], 't1.id=t2.tid');

count all results from a db query active records

$this->db->select('*')->from('myTable')->where('name',$user_name)->get()->results_array();
If i do this after the query above,
echo $this->db->count_all_results();
Even though myTable has rows :
Table: myTable Column1 name: id Column2 name: name
row1 - 1 row1 - peter row2 - 2 row2 - peter
It would echo 1, although there are 2 peters. My thoughts is that i returned the results as an array.
How should i return the results? Active_records class does not show how to. It only shows another format where i type in the query myself manually. I don't like doing queries like that.
Although might i ask for professionals' opinion. Which is better. The way im doing it or the examples in active records like,
$query = $this->db->get('mytable');
Although they dont show an example where you specifically select column names.
You should do it in 2 steps.
$query = $this->db->select('*')->from('myTable')->where('name',$user_name)->get();
$result = $query->result_array();
$countResult = $query->num_rows();

Better Way to return multiple SQL Queries in one PHP page

I am writing a website to compare cars to learn and understand PHP. I have a sql table of cars - one are of say ford - which as a company id of 1 in my another table. There is also a ModelLinkNo column in the table to link say saloon cars from Ford to saloon cars from BMW (which has a companyId of 2).
I want to display first a list of all ford company cars so my query is like below:
$getFordCars = sprintf("SELECT * FROM Cars WHERE CompanyId = '1'");
I then have multiple other querys below to bring back other cars which are off the same model - so like below:
$getSaloonCars = sprintf("SELECT * FROM CarsWHERE (CompanyId != '1' AND ModelLinkNo = '1')");
There are then other querys for get 4*4s get Hatchback, convertible, etc.
The data comes back from DB fine and I am wrting it to array as below:
<?php
$fordCars = array();
$otherSaloonCars = array();
$i = 0;
while($row = mysql_fetch_array($fordCarsResult))
{
$fordCars [$i]= $row['ModelName'];
$i++;
}
$j = 0;
while($row2 = mysql_fetch_array($otherSaloonCarsResult))
{
$otherSaloonCars [$j]= $row2['ModelName'];
$j++;
}
?>
The above works and then I can retrieve the data for displaying further in my page - however is there a better way of doing this rather than having multiple while loops - as when I return all convertible models that would be another query and return 4*4's that will be another query and using the pattern I am using now that would result in writing a while loop for each query to write the results into an array
Well, how about just downloading every ford car, and check on your backend site, if CompanyId is 1, or not, and pushing the data to the given array?
Also consider looking up for JOIN-ing your Cars table to itself, if needed.

Select players as team and mark in db as selected

i have one table named players with 2 columns: players and status
I need to select unique random teams!
Every team has X players as: Y base and Z pivots
Y and Z its set due input form
If in insert 3 for base and 2 for pivots The result should be like 3 teams or 3 players:
team 1
Base 1
Pivot 1
Pivot 2
team 2
Base 1
Pivot 1
Pivot 2
team 3
Base 1
Pivot 1
Pivot 2
After i generate teams i must be able to set status as "selected". If i need to create another team all users with status "selected" can't be use in another new team!
I currently use:
$nteams=$_POST['teams'];
$nbase=$_POST['base'];
$npivots=$_POST['pivots'];
$allplayers=$nteams*($nbase+$npivots);
require_once "connect_to_mysql.php";
$sqlCommand = "SELECT id FROM players ORDER BY RAND() LIMIT $allplayers";
$query = mysql_query($sqlCommand) or die (mysql_error());
if(mysql_num_rows($query)<$allplayers) // sanity
die('Not enough players!');
else
for($team=1;$team<=$nteams;$team++)
{
for($base=1;$base<=$nbase;$base++)
{
$row = mysql_fetch_array($query);
echo "Team $team Base $base = {$row['id']}<br />";
}
for($pivot=1;$pivot<=$npivots;$pivot++)
{
$row = mysql_fetch_array($query);
echo "Team $team Pivot $pivot = {$row['id']}<br />";
}
}
mysql_close();
Add WHERE status<>'selected' to your $sqlCommand statement
Store all read IDs from the database in an array, e.g. $selectedIds
Run update script UPDATE players SET status='selected' WHERE id IN ('.implode(',', $selectedIds).')
Side notes:
Consider rewriting the whole loop. It can be done in one while loop and one cursor/flag - let this be a homework :)
Beware of SQL Injection
You can wrap SELECT and UPDATE in a transaction to avoid inconsistency and conflicts

mysql update query syntax

I'm trying to use the following query syntax from a php file:
$sql = "UPDATE properties SET properties.ht_hs = 3.5 WHERE properties.oil_data_id = acea.oil_data_id AND (acea.ACEA_A3 = 1 OR acea.ACEA_B3 = 1 OR acea.ACEA_B4 = 1) AND properties.ht_hs < 3.5";
$result = mysql_query($sql) or die(mysql_error());
However, It's not doing what I want. I have two tables in my database, and I need to change the value of some of the records for one column within one of the tables (the ht_hs column/field within the properties table). However,the criteria for when to change that field is dependent upon both tables.
Each motor oil in the database has an id, which is listed in the "oil_data_id" column of each table.
I'm trying to find oils that meet the ACEA A3 or B3 or B4 spec (ie, they have a "1" in that column of the acea table) which also have a value of less than 3.5 in the ht_hs column of the properties table.
If they do, I want to update the value to 3.5.
How can I restructure my query so that it works?
I think you're looking for something like this:
UPDATE properties
SET properties.ht_hs = 3.5
WHERE properties.oil_data_id in
(select acea.oil_data_id
from acea
where (acea.ACEA_A3 = 1 OR acea.ACEA_B3 = 1 OR acea.ACEA_B4 = 1))
AND properties.ht_hs < 3.5;
You would need to include table acea in the JOIN like :-
UPDATE properties, acea
SET ...;
See the documentation
UPDATE items,month SET items.price=month.price
WHERE items.id=month.id;

Categories