mysql get data by matching row of fixed position with strlength() - php

I have a table where a filed contains roll numbers like so:
id | roll_no
--------------
1 | 290320452
2 | 290320453
3 | 290340454
4 | 290330455
from the above column I want roll_no with matching position 4 AND 5 with 32.
where the result would be
id | roll_no
--------------
1 | 290320452
2 | 290320453
For now I have done by filtering the result array like so:
$subject_code = 32;
foreach($result as $row){
if($subject_code != NULL){
if(substr($row['roll_no'],3,2) == $subject_code){
$data[] = $row['roll_no'];
}
}
else{
$data[] = $row['roll_no'];
}
}
Is there a better way to filter while querying on mysql query.
I have seen SUBSTRING() function of mysql but no help.

select roll_no from your_table
where substring(cast(roll_no as char(11)), 4, 2) = '32'

How about this:
You can use _ (underscore) as wild card to match exact number of positions.
select
id, roll_no
from
roll_numbers_table
where
roll_no like '___32%'; // 3 underscores before 32
This statement on your sample data would result:
id | roll_no
--------------
1 | 290320452
2 | 290320453

Related

do the math for each data in database sql post result to database in php

I'd like to fetch data from my 2 sql database and do some math and post the result in database
let's say my table1 is like this
+---+---+----------------------------+
| A | B | C |
+---+---+----------------------------+
| 2 | 9 | result from A*B*D*E in php |
| 1 | 8 | result from A*B*D*E in php |
| 4 | 7 | result from A*B*D*E in php |
| 3 | 6 | result from A*B*D*E in php |
| 6 | 5 | result from A*B*D*E in php |
| 6 | 5 | result from A*B*D*E in php |
| 5 | 4 | result from A*B*D*E in php |
+---+---+----------------------------+
and my table2 is like this
+---+----+
| D | E |
+---+----+
| 1 | 9 |
| 2 | 7 |
| 3 | 8 |
| 4 | 6 |
| 5 | 5 |
| 6 | 3 |
| 7 | 2 |
+---+----+
so far what i've done
// database connection
include_once("config.php");
// Query
$query = mysqli_query($conn, "SELECT * FROM table1");
$query2 = mysqli_query($conn, "SELECT * FROM table2");
//Source1
while($user_data1 = mysqli_fetch_array($query))
{
$A[] = $user_data1['A'];
$B[] = $user_data1['B'];
}
//Source2
while($user_data2 = mysqli_fetch_array($query2))
{
$D[] = $user_data2['D'];
$E[] = $user_data2['E'];
}
foreach (array_combine($A, $B) as $ValueA=> $ValueB)
{
foreach (array_combine($D, $E) as $ValueD=> $ValueE)
{
$result1 = $ValueA*$ValueB*ValueD*ValueE;
$val = 0.123;
$result2[] = $result1*$val;
}
$final result = min($result2);
echo round($final result, 2);
unset($result2);
}
I haven't inserted the database yet
still echoing for debug if the math is correct
somehow this code found some bug
for example using my database the final result only echo/showing 6 math result
because in table1 row 5 and 6 has same data
btw of course in my table1 and 2 has primary key
To change C in this case, you don't even need PHP. To UPDATE a value in MySQL with multiple tables just add them with a , when selecting the tables, like this:
UPDATE table1,table2 SET C = table1.A * table1.B * table2.D * table2.E WHERE C IS NULL;
Executing this code once will update all rows so that C = A*B*D*E as wanted where C is not yet set or NULL. If you want to update all rows you can just remove the WHERE condition
Note: Sometimes (at least for me) SQL will give a warning when having no WHERE condition in the SQL query. To bypass this just add WHERE 1=1 at the end.
Just for my understanding: you want to calculate a value for your calculation you need some data from table 1 that is clear, but also from table2 But which one? I guess you want to use the data from the same row ( so row 1 from table1 and row 1 from table2, row 2 from table 1 and row 2 from table2 ) right? Now you have an problem because when you make a select * from table You do not know in which order they give back from your database. Most time it may be the same order as you have input them, but there is no garantie. You have sayed you have an primary key on each table, how have you defined them? I guess you may have a id column, so you can join your table on that id?

PHP + SQL -- Counting clicks in multiple rows

i stuck at the problem that my code wont count total clicks in multiple rows.
This is how the Database looks
id | jb_clicks | created_time
--------------------------------------------------
1 | 14 | 1475420816
2 | 7 | 1475422200
3 | 9 | 1475422217
4 | 3 | 1475422239
I want the result to be 33 (14+7+9+3)
How is this possible?
The current code looks like this:
SELECT COUNT(*) AS jb_clicks FROM jb_urls
my function:
function sumdatabase($select, $statement){
$config = new mysql_config;
$link = mysqli_connect($config::MYSQL_HOST,$config::MYSQL_USER,$config::MYSQL_PASS);
mysqli_select_db($link, $config::MYSQL_DATABASE);
$result = mysqli_query($link,"SELECT SUM(".$config::MYSQL_PREFIX."$select) AS jb_clicks FROM $statement");
$row = mysqli_fetch_assoc($link,$result);
return $row[$config::MYSQL_PREFIX.$select];
}
Use the following:
SELECT SUM(jb_clicks) AS jb_clicks FROM jb_urls
COUNT() is used to count the row numbers and SUM() is to calculate the total sum of a column in a table. In your case, it would be SUM(jb_clicks).

MySQL Select Multiple Row with column value

I have a table has columns tag_id and item_id,
---------------------
| tag_id | item_id |
---------------------
| 1 | 2 |
| 2 | 2 |
| 4 | 2 |
| 3 | 5 |
| 5 | 7 |
| 11 | 5 |
---------------------
For example, I want to return item_id = 2 if I input tag_id = 1,2,4
what is the query should look like?
I am using Codeigniter.
If you are looking for Msql query that returns only one cell value you can use the following:
SELECT DISTINCT item_id FROM tableName WHERE tag_id IN (1, 2, 4)
Try this code.Will help you
$this->db->select('item_id');
$this->db->from('tblNAME');
$where = "tag_id='1' OR tag_id='2' OR tag_id='2 ";
$this->db->where($where);
return $this->db->get()->result();
Try this:
select * from table where tag_id in (1,2,4)
Thank you all answers but unfortunately not suitable for the use. Because I want it return exactly the item id = 2 if tag id = 1,2,4.
If we using IN(1,2,4) it will return item ids that has tag id 1 or 2 or 4.
Finally I figure out the SQL query should be
Select *, COUNT(item_id) AS id_count
FROM TABLE_NAME
WHERE tag_id IN(1,2,4)
GROUP BY item_id HAVING id_count = 3
Therefore, express it in a general form, we simply replace the 3 by the size of the array of tag id.

PHP Mysql MAX() returning wrong result

PHP:
$result = mysql_query("SELECT MAX(something) AS something FROM users");
$row = mysql_fetch_assoc($result);
$max = $row["something"];
echo $max;
Mysql:
+-----------+----------+
| Something | Name |
+-----------+----------+
| 9 | John |
| 984 | Somebody |
| 1 | Who |
Code results: 9, the question is why? Mysql "something" type is "text". My mysql table is bigger than this above, but it still results not the biggest "something".
Either do a math operation on the column to trigger an auto-cast
SELECT MAX(something * 1) AS something FROM users#
or cast explicitly with
SELECT MAX(cast(something as signed)) AS something FROM users
but even better - if that column only contains numbers then change the data type of that field ti int for instance.

Count same values in different column mysql

I need to count how many times in ripeted the same values in different columns for the same id..
I'll try to clarify with an example:
TABLE:
+-----+-----+-----+-----+-----+
| id | d01 | d02 | d03 | d04 |
+=====+=====+=====+=====+=====+
| 1 | A | A | B | B |
+-----+-----+-----+-----+-----+
| 2 | A | A | A | A |
+-----+-----+-----+-----+-----+
| 3 | B | B | A | A |
+-----+-----+-----+-----+-----+
| 4 | A | A | A | A |
+-----+-----+-----+-----+-----+
| 5 | A | A | A | A |
+-----+-----+-----+-----+-----+
| 6 | B | A | A | A |
+-----+-----+-----+-----+-----+
I need to know how many times the value "B" is repeating for any person (ID)..
Is that possible to do that? RESULTS
+-----+-----+-----+
| id | count B |
+=====+=====+=====+
| 1 | 2 |
+-----+-----+-----+
| 2 | 0 |
+-----+-----+-----+
| 3 | 2 |
+-----+-----+-----+
I was thinking to use the function "SUM" but I have no idea how to display just the single ID.
Thanks in advance, hope the question is clear enough!
If there are only four columns:
SELECT id, (d01 = 'B') + (d02 = 'B') + (d03 = 'B') + (d04 = 'B')
FROM tablename
No there are 31 columns
That's a problem which you can solve in two ways:
Repeat the condition for the other 27 columns :)
Normalize your structure so that each value is dependent on both the id and a numeric value that represents a calendar.
The PHP way
You can also fetch all columns and let PHP solve this for you:
$res = $db->query('SELECT * FROM tablename');
foreach ($res->fetchAll(PDO::FETCH_ASSOC) as $row) {
$id = $row['id'];
unset($row['id']); // don't count the id column
$count = count(array_keys($row, 'B', true));
printf("ID %d: %d\n", $id, $count);
}
Since you seem to be using mysql_*:
// SHOW COLUMNS returns all the columns and constrains of the defined table
// We only need the column names so we will be later calling it by 'Field'
$sql = mysql_query("SHOW COLUMNS FROM table"); //your table name here
$val_to_count = 'B'; //value to count here
$id = 1; //id to search for
$new_sql = 'SELECT id, ';
// In this loop we will construct our SELECT query using the columns returned
// from the above query
while($row=mysql_fetch_array($sql)){
if($row['Field']!='id'){
$new_sql .= ' ('.$row['Field'].' = "'.$val_to_count.'") + ';
}
}
//Removing the last "+ " produced in the select query
$new_sql = rtrim($new_sql,"+ ");
$new_sql .= ' as count FROM table WHERE id = '.$id; //table name here again
// so $new_sql now has an output like:
// SELECT ID, (d01 = 'B') + (d02 = 'B') ... WHERE id = 1
$sql2 = mysql_query($new_sql);
//executing the constructed query with the output below
while($row2=mysql_fetch_array($sql2)){
echo 'ID - '.$row2['id']."<br>";
echo 'Count - '.$row2['count']."<br>";
}
Note:
mysql_* is deprecated, please consider to migrate to mysqli_*

Categories