php retrieve multiple data from mysql - php

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";
}

Related

PHP: copy MySQL database tables into new database table with additional columns

I am looking for a way to copy an existing database with multiple tables into a new database with the same tables and columns + some additional columns. So far so good. If I just copy the database to a new database with the same amount of tables and columns I am doing it like this:
+---------+---------+---------+
| TABLE 1 | | |
+---------+---------+---------+
| Col1 | Col2 | Col3 |
| Value 1 | Value 2 | Value 3 |
| Value 1 | Value 2 | Value 3 |
| Value 1 | Value 2 | Value 3 |
+---------+---------+---------+
copy to:
+---------+---------+---------+
| TABLE 2 | | |
+---------+---------+---------+
| Col1 | Col2 | Col3 |
| Value 1 | Value 2 | Value 3 |
| Value 1 | Value 2 | Value 3 |
| Value 1 | Value 2 | Value 3 |
+---------+---------+---------+
Code:
public function loadDB($db1,$db2){
$this->db->prepare("use ".$db1."");
$sqlshow = "SHOW TABLES ";
$statement = $this->db->prepare($sqlshow);
$statement->execute();
$tables = $statement->fetchAll(PDO::FETCH_NUM);
foreach($tables as $table){
$sql[] = "INSERT INTO ".$db2.".".$table[0]." SELECT * FROM ".$db1.".".$table[0]."; ";
}
$sqlState = implode(' ', $sql);
$insertStatement = $this->db->exec($sqlState);
return $insertStatement?$insertStatement:false;
}
This code works and my database is copied successfully with all my tables and values inside my tables. What I need now is a working example of how am I able to copy the database to a new database where all tables have four additional columns like this:
+---------+---------+---------+
| TABLE 1 | | |
+---------+---------+---------+
| Col1 | Col2 | Col3 |
| Value 1 | Value 2 | Value 3 |
| Value 1 | Value 2 | Value 3 |
| Value 1 | Value 2 | Value 3 |
+---------+---------+---------+
copying to:
+---------+---------+---------+-----------+-----------+-----------+-----------+
| TABLE 2 | | | | | | |
+---------+---------+---------+-----------+-----------+-----------+-----------+
| Col1 | Col2 | Col3 | Counter | LoadDay | User | UserNew |
| Value 1 | Value 2 | Value 3 | NEW VALUE | NEW VALUE | NEW VALUE | NEW VALUE |
| Value 1 | Value 2 | Value 3 | NEW VALUE | NEW VALUE | NEW VALUE | NEW VALUE |
| Value 1 | Value 2 | Value 3 | NEW VALUE | NEW VALUE | NEW VALUE | NEW VALUE |
+---------+---------+---------+-----------+-----------+-----------+-----------+
Code (what I´ve tried so far):
public function loadDB($db1,$db2,$condition){
$this->db->prepare("use ".$db1."");
$sqlshow = "SHOW TABLES ";
$statement = $this->db->prepare($sqlshow);
$statement->execute();
$tables = $statement->fetchAll(PDO::FETCH_NUM);
foreach($tables as $table){
$sqlshow2 = "SHOW COLUMNS FROM ".$table[0]." ";
$statement = $this->db->prepare($sqlshow2);
$statement->execute();
$columns = $statement->fetchAll(PDO::FETCH_NUM);
foreach($columns as $column){
$sql[] = "INSERT INTO ".$db2.".".$table[0]." SELECT ".$column[0]." FROM ".$db1.".".$table[0]."; ";
}
$sql[] .= "INSERT INTO ".$db2.".".$table[0]." (`Counter`, `LoadDay`, `User`, `UserNew`) VALUES ('1', '".date("Y-m-d H:i:s")."', '".$condition."', '".$condition."')";
}
$sqlState = implode(' ', $sql);
var_dump($sqlState);
$insertStatement = $this->db->exec($sqlState);
return $insertStatement?$insertStatement:false;
}
The creation of the databases are working (not visible in my posted code here). I only get no values copied to my new tables inside my new database. What am I doing wrong here?
Your final SQL query comes out wrong. I suggest changing your code to somthing like this:
foreach($tables as $table){
$sqlshow2 = "SHOW COLUMNS FROM ".$table[0]." ";
$statement = $this->db->prepare($sqlshow2);
$statement->execute();
$columns = $statement->fetchAll(PDO::FETCH_NUM);
$sql[] = "INSERT INTO ".$db2.".".$table[0]." SELECT * , '1', '".date("Y-m-d H:i:s")."', '".$condition."', '".$condition."'" . " FROM ".$db1.".".$table[0]."; ";
}

How to query based on multiple relations between columns - MySQL?

I have four columns in a properties table: property_id, value, id, material_id.
I also have an array of properties: Array $properties
The schema is a bit complicated, because I want to find the material_id based on the matching properties.
An example:
$properties = array(['property_id'=>1,'value'=>3],['property_id'=>2,'value'=>6],['property_id'=>3,'value'=>4]);
Example table output:
+----+-------------+-------------+-------+
| id | material_id | property_id | value |
+----+-------------+-------------+-------+
| 1 | 1 | 3 | 5 |
| 2 | 1 | 3 | 5 |
| 3 | 1 | 3 | 5 |
| 4 | 2 | 1 | 3 |
| 5 | 2 | 2 | 6 |
| 6 | 2 | 3 | 4 |
| 10 | 4 | 1 | 9 |
| 11 | 4 | 2 | 3 |
| 12 | 4 | 3 | 6 |
+----+-------------+-------------+-------+
Now, I need material_id that satisfies all the properties. How can I do that..? Do I need to use exist statement of MySQL?
Now, for each element in your array you will want to run a statement that looks like this:
SELECT material_id FROM properties WHERE property_id = 2 AND value = 3;
Do you need help on the php code also? You could run a for each loop, but I will need to know what way you are using to communicate with your database for more specifics.
edit
foreach ($properties as $foo => $bar)
{
$sql = 'SELECT material_id FROM properties WHERE ';
foreach ($bar as $key => $value)
{
$sql .= $key .' = '. $value .' AND ';
}
$sql .= 'true';
*run your PDO code on $sql here*
}
On behalf of performance, it's not a good idea to run a query per array's value. If you have an oversized array things can get pretty slower.
So, best solution can be to build a single query including all conditions presented on $properties array:
<?php
$properties = array(['property_id'=>1,'value'=>3],['property_id'=>2,'value'=>6],['property_id'=>3,'value'=>4]);
$qCondition = [];
foreach($properties as $prop) {
$q = sprintf("(property_id = %d AND value = %d)", $prop["property_id"], $prop["value"]);
$qCondition[] = $q;
}
// assuming that your database table name is 'materials'
$sql = sprintf("SELECT * FROM materials WHERE (" . implode(" OR ", $qCondition) . ")");
echo $sql;
Result:
SELECT * FROM materials
WHERE ((property_id = 1 AND value = 3) OR (property_id = 2 AND value = 6) OR (property_id = 3 AND value = 4))
Therefore, you need to run only one single query to get all desired rows.
You can play with suggested solution here: http://ideone.com/kaE4sw

Is it possible to sort Array Value with Array Value?

I have an example like this:
code | name
a | Pencil
b | Pen
d | Ruler
g | TipeX
-
no | data | list_order
1 | b,d,a | 2,3,1
2 | g,b,a | 3,2,1
So when run the query the data will be like this:
no | data | list_order
1 | b | 2
1 | d | 3
1 | a | 1
Then I can sort it by list_order ASC
no | data | list_order
1 | a | 1
1 | b | 2
1 | d | 3
My question, is it possible to get the query like above?
*I'm using Oracle DB
$q_data = oci_parse($c1, "SELECT * FROM DATAS WHERE NO = '1'");
oci_execute($q_data);
$row = oci_fetch_array($q_data);
$cp_array = implode(",",array($row['data']));
$cp_list_order = implode(",",array($row['list_order']));
$q_data_cp = oci_parse($c1, "SELECT * FROM DATAS_DTL WHERE no IN ($cp_array)");
oci_execute($q_data_cp);
while($d_data = oci_fetch_array($q_data_cp))
{
$d_no = $d_data['no'];
$d_name = $d_data['name'];
?>
<div><?php echo $d_name; ?></div>
<?php
}
Thanks.
I don't use oracle db, but I use sql server and I think they both are similar in a lot of ways.
Try to do the following:
create a temp table
split the string using some kind of CROSS APPLY (see: How to split a comma-separated value to columns)
insert the splitted values inside the temp table
query the temp table

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!

Categories