$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();
Related
My database structure is like this:
Movie Name GenreID**
Movie1 1,2,3
Movie2 2,4
Movie3 4,5,16
I need to select a Movie name based on the Genre ID the user selected which I put inside the genreIDArray[]
Let's say for example the genreIDArray has values: $genreIDArray = ['1','2','3'];
My current query method is the ff:
Here I prepared each ID into parts so the result won't become genreID LIKE (%1,2,3%) because I checked this doesn't work.
So I did this separation loop:
$queryParts = array();
foreach($genresIDArray as $genreID) {
$queryParts[] = "'%".$genreID."%'";
}
After the separation loop I put together the final query:
$genreString = implode(" OR genreID LIKE ",$queryParts);
$genreQuery = " SELECT * FROM movies WHERE (genreID LIKE {$genreString}) ";
gave me this final query output:
SELECT * FROM movies WHERE (genreID LIKE '%1%' OR genreID LIKE '%2%' OR genreID LIKE '%3%')
This actually works, but apparently not that efficient because genreID 11,12,13 and so on that start with 1 is also selected. I think I'm missing the MYSQL LIKE logic here. I've tried '%$genreID' which means to select the starting or first number/letter of a table data, but that's still the same thing, $genreID% doesn't and would not work because this only means genreid ENDING letters/number will be selected.
I hope I spelled that out clear enough. I'm in a bind here. Please help.
Thank you so much.
There is a very cool function for that. You can use FIND_IN_SET.
SELECT * FROM test WHERE FIND_IN_SET(1,colors)
But if its possible you should avoid such structures in your database and normalize your database.
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);
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/>";
}
I run the following query:
SELECT tagID,
COUNT(*) AS TotalOccurrences
FROM coupon_tags
GROUP BY tagID
ORDER BY TotalOccurrences DESC
LIMIT 10
It returns output like this:
tagID TotalOccurrences
------------------------
7 9
2 8
1 3
6 2
3 1
4 1
5 1
8 1
I can't do a mysql_fetch_array(mysql_query($thatQuery); because it has two columns of data and any array pulled looks like garbage. How can I further streamline that query to a single column of still-sorted data, so it's easier to work with in an array? Or maybe I am using the wrong PHP/MySQL function (although I looked through them all)?
Edit: I've found out that the query will work fine in phpMyAdmin but it fails when I try to query with mysql_query().
My php code:
$tagSQL = mysql_query($selectorSQL);
if (!$tagSQL) die("query failed"); //fails here
while ($tSrow = mysql_fetch_assoc($tagSQL)) {
var_dump($tSrow);
}
You can do it like this to "streamline that query to a single column of still-sorted data".
SELECT tagID
FROM coupon_tags
GROUP BY tagID
ORDER BY COUNT(tagID) DESC
LIMIT 10
Just make sure to use count on a single column instead of counting everything, this will greatly affect performance.
Don't try and do everything in one line. Makes it hard to debug.
$sql = "SELECT ...";
$result = mysql_query($sql);
if (!$result) die("query failed");
while ($row = mysql_fetch_assoc($result)) {
var_dump($row);
}
Using PHP mysql_num_rows() returns "1" when running the query below on the table below when there are no matching rows present.
Upon testing I found out that the problem happens when I use the SUM() function in the query. If I take SUM() out of the query mysql_num_rows() returns "0" like it should.
Is there something else I should use instead of mysql_num_rows() to find out if there is a matching row in the table?
Table:
name | students_money | grade
George | 5 | A
Bill | 10 | A
Dan | 7 | A
Code:
$sql = "SELECT SUM(students_money) AS sum_money FROM students_table WHERE name = 'Tom' AND name = 'Jack'";
$result = #mysql_query($sql, $con) or die(mysql_error());
$num_rows = mysql_num_rows($result);
if ($num_rows < 1) {
echo "not everyone has paid";
exit;
}
while($row = mysql_fetch_array($result)) {
$sum_money = $row[sum_money];
$total = $total + $sum_money;
}
SUM() is an aggregate function. It takes all the rows that are returned for a group and adds them up.
Since you do not have a GROUP BY clause, it is adding up the values of all rows, even if there are none. It is then returning the total as a single row, so there should only be 1 row.
If you clarify what you want returned, I can try to help you write a statement to return it.
mysql_num_rows() tells you the number of rows returned by the database query. There is always a one row return in your case because there is always one a sum. The sum may be 0 of course.
It may be a good idea to test your query in the mysql query browser. Perhaps you are looking for something like this?
SELECT name, SUM(students_money) AS sum_money
FROM students_table
GROUP BY name;
This will group the sums on a per name basis. To skip 0 sums you can add this:
HAVING sum_money > 0;