Getting data from array to reference other table - php

Im trying to get data from one table based upon the date in a column from another table. I've tried using an inner join but I can't quite figure out how to make it do what I want. Below is an example. Basicly the numbers in the rules column will referance the rule_id in the infraction rules table. Then output the rule long name in readable text.
user_infractions table
+--------+-----------------+------------------+----------------+
|ban_id | name | username | rules |
+--------+-----------------+------------------+----------------+
| 2 | bob | Bob | 2,7, |
| 7 | dave | dave1 | 3,5, |
+--------+-----------------+------------------+----------------+
infraction_rules table
+--------+-----------------+------------------+----------------+
|rule_id | rule number | short_name | long_name |
+--------+-----------------+------------------+----------------+
| 2 | 1.2.2 | Rule 2 | Rule 2 Long Na |
| 7 | 1.2.7 | Rule 7 | Rule 7 Long Na |
+--------+-----------------+------------------+----------------+
Below is the code im using to try to achieve this
$string = $row['rules']; //data from table as a string
$strtrim = rtrim($string,","); //removed trailing comma from string
$violations = explode(",", $strtrim); // string to array conversion
foreach($violations as $violation) {
echo $violation;
$sql3 = "SELECT *
FROM user_infractions
INNER JOIN infraction_rules ON user_infractions.rules = infraction_rules.rule_id
WHERE user_infractions.rules = ?;";
$stmt3 = $conn->prepare($sql3);
//$stmt -> mysqli_stmt_prepare($stmt, $sql);
$stmt3->bind_param("s", $violation);
$stmt3->execute();
$result3 = $stmt3->get_result();
if ($result3->num_rows > 0) {
while ($row3 = $result3->fetch_assoc()) {
echo $row3['rule_long_desc'];
}
}
}

Related

Check if a certain element is in a table MySQL database

I need to check if a certain element is in the table.
Table I am using:
+----------+------------+-------------------+
| ClientId | ClientName | ClientCountryName |
+----------+------------+-------------------+
| 1 | Chris | UK |
| 2 | David | AUS |
| 3 | Robert | US |
| 4 | Mike | ENG |
+----------+------------+-------------------+
This is the code I made, is there a better way?
$c=0;
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
if('US'==$row['ClientCountryName']){
$c=$c+1; //If the element is in the table, increment c
}
}
if($c!=0){ //if c is incremented means that the element is one or multiple times in the table
echo 'Element is in the table';
}
else{ //if c is not incremented then the element is not in the table
...
}
You can use count to return count of elements containing US
select count(*)
from users
where ClientCountryName like 'US'
Thanx!

Fetching data from a table and storing in variables

I have website settings stored in a table like this:
+---------+-------------+
| id | value |
+---------+-------------+
| 1 | title |
| 2 | description |
| 3 | email |
| 4 | keywords |
+---------+-------------+
How can I select them and assign them to variables ($title, $desc, $email, $key)
// Get Website Infos
$result=$db->query("SELECT `value` FROM `settings`");
if($result->num_rows >= 1){
$row=$result->fetch_assoc();
$otitle=$row['value'];
$odescription=$row['value'];
$oemail=$row['value'];
$okeywords=$row['value'];
}
but it only get the first row 'title',any idea how to do it or better way to save settings.
UPDATE:
If you are reading this question now, don't use this structure to store your settings, use the one suggested by Yellow Bird in the answers.
You have to loop with your fetch_assoc() method :
$result = $db->query("SELECT `value` FROM `settings`");
if ($result->num_rows >= 1){
$data = array();
while ($row = $result->fetch_assoc()) {
$data[] = $row['value'];
}
}
var_dump($data);
As DanFromGermany noticed in comments, your db structure is probably not done the right way. You should have a design like this :
+---------+-------------+--------------+
| id | key | value |
+---------+-------------+--------------+
| 1 | title | title value |
| 2 | description | desc value |
| 3 | email | email value |
| 4 | keywords | keyw value |
+---------+-------------+--------------|
And then, your code would look like this :
$result = $db->query("SELECT key, value FROM `settings`");
if ($result->num_rows >= 1) {
$data = array();
while ($row = $result->fetch_assoc()) {
$data[$row['key']] = $row['value'];
}
}

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_*

PHP and MySQL, array associated with 2 keys

I have this scenario.
I input $groupid="1";
main table
----------------------
| groupid | postid |
|---------------------|
| 1 | 1 |
| 2 | 2 |
| 1 | 3 |
$query = "SELECT postid FROM `mainl` WHERE groupid='$groupid'";
$result = mysql_query($query);
// a group of postids belonging to that groupid which should hold [1, 3] for groupid=1
while($row = mysql_fetch_array($result)) {
$postids[] = $row["postid"];
}
second table
-------------------------------------------
| postid | commentid | comment |
-------------------------------------------
| 1 | 1 | testing 1 |
| 1 | 2 | testing 2 |
| 1 | 3 | what? |
| 2 | 1 | hello |
| 2 | 2 | hello world |
| 3 | 1 | test 3 |
| 3 | 2 | begin |
| 3 | 3 | why? |
| 3 | 4 | shows |
$query = "SELECT * FROM `second`";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
if (in_array($row["postid"], $postids)) {
$comments[$row["postid"]] = $row["comment"];
But how should I take care of commented
I want the postid array to be [1,3] and my comment array to be
[commentid: comment] [1:testing1, 2: testing2, 3: what?] for postid=1
and
[1:test3, 2:begin, 3: why? 4:shows] for postid=3
how should be arrange everything such comment are associated with commentid and postid?
First I would follow rokdd suggestion and make 1 query
SELECT m.groupid , s.postid, s.commentid, s.comment FROM `main1` m JOIN `second` s USING (postid) where m.groupid = 1
Then I would make a multi-dimensional array
while ($row = mysql_fetch_array($result))
$groups[$row['groupid'][$row['postid']][$row['commentid']=$row['comment'];
then to iterate through the array
foreach($groups as $group)
foreach($group as $post)
foreach($post as $comment)
echo $comment;
This will keep track of groups also (if you ever want to select by more than 1 group.
If you don't care about groups just drop off the first part of the array.
while ($row = mysql_fetch_array($result))
$posts[$row['postid']][$row['commentid']=$row['comment'];
foreach($posts as $post)
foreach($post as $comment)
echo $comment;
I guess to use the join in sql so that you will have one statement:
SELECT * FROM second as second_tab LEFT join main as main_table ON main_table.post_id=second_table.post_id WHERE main_table.group_id="3"
Well not tested now but thats a way to solve some of your problems!

php retrieve multiple data from mysql

I insert multiple id from my checkbox to MySQL database using php post form. In example I insert id (checkbox value table test) to mysql. Now I need a function to retrieve data from MySQL and print to my page with my example output (print horizontal list name of table test where data = userid)
My checkbox value (table name is test):
id | name
----+-------
1 | test1
2 | test2
3 | test3
4 | test4
5 | test5
6 | test6
7 | test7
9 | test9
MySQL data insert (name of table usertest):
id | data | userid
----+---------+--------
1 | 1:4:6:9 | 2
2 | 1:2:3:4 | 5
3 | 1:2 | 7
Example outout :( print horizontal list name of table test where data = userid )
user id 2 choise : test1 - test4 - test6 - test9
Thanks
Assuming your usertest table has only the three columns listed in your example you should replace it with the following -
CREATE TABLE usertest (
data INTEGER NOT NULL,
userid INTEGER NOT NULL,
PRIMARY KEY (data, userid)
);
Then your data will look like -
+------+--------+
| data | userid |
+------+--------+
| 1 | 2 |
| 4 | 2 |
| 6 | 2 |
| 9 | 2 |
| 1 | 5 |
| 2 | 5 |
| 3 | 5 |
| 4 | 5 |
| 1 | 7 |
| 2 | 7 |
+------+--------+
Querying this data then becomes trivial -
SELECT usertest.userid, GROUP_CONCAT(test.name SEPARATOR ' - ')
FROM usertest
INNER JOIN test
ON usertest.data = test.id
GROUP BY usertest.userid
You can read more about GROUP_CONCAT here
You could use a PHP solution and store the possible checkbox values in an array indexed by their ids. Something like -
<?php
$db = new PDO('mysql:dbname=test;host=127.0.0.1', 'user', 'pass');
$sql = 'SELECT id, name FROM test';
$stmt = $db->prepare($sql);
$stmt->execute();
$array = array();
while ($row = $stmt->fetchObject()) {
$array[$row->id] = $row->name;
}
$sql = 'SELECT userid, data FROM usertest';
$stmt = $db->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetchObject()) {
$data = explode(':', $row->data);
foreach($data as $key => $val) {
$data[$key] = $array[$val];
}
print "user id {$row->userid} choise : " . implode(' - ', $data) . "<br/>\n";
}

Categories