I have a dynamic Matrix box where users can unlimited drugs, the data comes through like this:
[addindividuals] => [{"Drug":"Calpol","Strength":"100mg","Form":"Liquid","Quantity":"1"},{"Drug":"Paracetamol","Strength":"200mg","Form":"Tablet","Quantity":"16"}]
What I'm trying to achieve is to have each line inserted into a new row (MySQL) and inserts into their relevant columns like so:
Columns: | Drug | Strength | Form | Quantity
Row1 | Calpol | 100mg | Liquid | 1
Row2 |Paracetamol | 200mg | Tablet | 16
I'm guessing its using the exploded function> (I'm a novice) and then sql to insert the strings?
If you have the values as a json string collection, First you need to explode then the string then use a for each to loop through each string then use another for each to make single row. Please have a below code this may help you.
$addindividuals = '{"Drug":"Calpol","Strength":"100mg","Form":"Liquid","Quantity":"1"},{"Drug":"Paracetamol","Strength":"200mg","Form":"Tablet","Quantity":"16"}';
$exploded_array = explode('},',$addindividuals);
$final_query = "INSERT INTO `table_name` (`Drug`,`Strength`,`Form`,`Quantity`) VALUES ";
$exploded_array[0] = $exploded_array[0].'}';
foreach($exploded_array as $exploded_element)
{
$single_row = '(';
$json_decode = json_decode($exploded_element,true);
foreach($json_decode as $key => $value)
{
$single_row .= "'$value',";
}
$single_row = substr($single_row,0,-1);
$single_row .= '),';
$final_query .= $single_row;
}
$final_query = substr($final_query,0,-1);
echo $final_query;
Related
Please could someone help me? I want to select all values in mysql table where the column that i want to check get a value is mix with aingle or array of values....... So to be more clear I have a table to store all messages from many sender to one or many reciever....
my functions is
public static function find_messagesTo_by_user_id($mess_to=0) {
global $database;
$mess_to = $database->escape_value($mess_to);
$sql = "SELECT * FROM ".self::$table_name;
$sql .= " WHERE mess_to = '{$mess_to}'";
$sql .= " AND mess_deleted = 0";
$sql .= " ORDER BY mess_created_date DESC";
$result_array = parent::find_by_sql($sql);
return $resultrray;
}
So 'mess_to ' has array and single value .... they are only numbers Like (1, 15, 25 ,26 ,27 , array(1,25, 27) , 31, 42, .......)
Please, i break my head on it :)
I waiting for any help?
Building on #Maluchi's answer. Make sure your data looks like:
| mess_to |
+-----------------+
| ,123, |
| ,123,456,152,1, |
| ,456,567, |
| ,3, |
So surround each value in ,. then you can safely do:
WHERE `mess_to` LIKE "%,{$mess_to},%"
This ensures that $mess_to = 1 will match only the 2nd row, and not the 1st as well.
You could also denormalize your data and make a table to JOIN on.
If I'm reading it correctly, $mess_to is passed into the function and could contain either a single value or it could be passed in an array.
When matching multiple values, the SQL should be looking for a comma-separated list. The where clause needs to be IN the list rather than EQUAL to the list.
Try:
public static function find_messagesTo_by_user_id($mess_to=0) {
global $database;
$mess_to = $database->escape_value($mess_to);
$sql = "SELECT * FROM ".self::$table_name;
$sql .= " WHERE mess_to IN (" . implode(',', $mess_to) . ")";
$sql .= " AND mess_deleted = 0";
$sql .= " ORDER BY mess_created_date DESC";
$result_array = parent::find_by_sql($sql);
return $resultrray;
}
See this line in particular:
$sql .= " WHERE mess_to IN (" . implode(',', $mess_to) . ")";
Code edited with geomagas's comments! (Thank you geomagas!)
asuming your column is like this
| mess_to |
+---------+
| 1 |
| 1,2,3,4 |
| 2 |
| 3 |
you can use the LIKE operator:
$sql .= " WHERE mess_to LIKE '%{$mess_to}%'";
this will match every row where mess_to has the string value of $mess_to (your column data type should be string for this to work).
Hi guys just want to ask how can i store multidimensional array in mysql?
My table format is like this:
Sales Table
| sales id | fkmember | date_of_sales
Sales Line Table
| line id | fkproduct | fksales | qty_purchased
My array is this:
foreach($products as $element => $inner_array){
echo "<strong>Product ID: ".$element."</strong><br>";
foreach($inner_array as $items){
echo $items."<br>";
}
}
How can i put the data in my tables?
You can try serialization of array, very similar to what Wordpress does, to store configuration values
Use implode() function which turns the array of column values into a string.
foreach($inner_array as $items) {
$sql = "INSERT INTO Sales (salesid, fkmember, date_of_sales, lineid, fkproduct, fksales, qty_purchased ) VALUES ('" . implode("', '", $items) . "')";
$result = mysql_query($sql) or die(mysql_error());
}
I want to get text result like:
+----+-------+----------------------------------+----+
| id | login | pwd | su |
+----+-------+----------------------------------+----+
| 1 | root | c4ca4238a0b923820dcc509a6f75849b | 1 |
+----+-------+----------------------------------+----+
1 row in set (0.00 sec)
in PHP (string).
Example in php:
$query = mysql_query("SELECT * FROM users");
for (; $row = mysql_fetch_assoc($query); $data[] = $row);
I get array of arrays ($data):
$data =
0 => (id=>1, login=>root..)
But i want to get this as string:
+----+-------+----------------------------------+----+
| id | login | pwd | su |
+----+-------+----------------------------------+----+
| 1 | root | c4ca4238a0b923820dcc509a6f75849b | 1 |
+----+-------+----------------------------------+----+
1 row in set (0.00 sec)
By the way for query "insert into users set login = 'sp', pwd = 1, su = 0", this string must be "Query OK, 1 row affected, 2 warnings (0.18 sec)".
Like sql terminal though php!
Either invoke mysql client as an external command, or build the ASCII drawing table yourself. You can't get it purely by using PHP's MySQL library functions. Off the top of my head,
$result = `echo 'SELECT * FROM users' | mysql --user=username --password=password dbname`;
(ugly, slow, insecure, don't recommend); or simply get it as the array, iterate, and decorate with plusses imitating what mysql does (recommended). It's really easy.
However, I have no clue why you'd want that, unless you're using your PHP program as a command-line tool.
Collect the database result into an array of arrays(your $data variable is correct)
echo ascii_table($data);
I stole the following from someone named stereofrog
function ascii_table($data) {
$keys = array_keys(end($data));
# calculate optimal width
$wid = array_map('strlen', $keys);
foreach($data as $row) {
foreach(array_values($row) as $k => $v)
$wid[$k] = max($wid[$k], strlen($v));
}
# build format and separator strings
foreach($wid as $k => $v) {
$fmt[$k] = "%-{$v}s";
$sep[$k] = str_repeat('-', $v);
}
$fmt = '| ' . implode(' | ', $fmt) . ' |';
$sep = '+-' . implode('-+-', $sep) . '-+';
# create header
$buf = array($sep, vsprintf($fmt, $keys), $sep);
# print data
foreach($data as $row) {
$buf[] = vsprintf($fmt, $row);
$buf[] = $sep;
}
# finis
return implode("\n", $buf);
}
You can please query the following sql:
SELECT GROUP_CONCAT(id, ' | ', login, ' | ', pwd, ' | ', su)
AS 'User Object' FROM users group by id
Result Would Be:
I'm working through this tutorial online: http://goo.gl/qnk6U
The database table: ajax_search
Firstname | Lastname | Age | Hometown | Job
-------------------------------------------
Joe | Smith | 35 | Boulder | CIA
Steve | Apple | 36 | Denver | FBI
(Types are all varchar except age is an int.)
My question. Is the sql select statement below written correctly to query "Joe 35"? For some reason, I can only query "Joe" and it works, but not combining search terms.
$sql = "select * from ajax_search where FirstName like '%$rec%' or LastName like '%$rec%' or Age like '%$rec%' or Hometown like '%$rec%'";
Assuming your query is "Joe 35", then no. Your query matches any row where any of the four fields contains "Joe 35" (in a single field). To query for a user with name Joe and age 35, you'd need to split the search query and do something like:
WHERE Firstname LIKE "$firstname" AND Age LIKE "$age"
You need to split that sting from search query:
$columns = array("Firstname", "Lastname", "Age", "Hometown", "Job");
$string = ""; // acquire query string
$split = explode(" ", $string);
$search_words = array();
foreach ($split as $word) {
$search_words[] = $word;
}
Create query to search all over the fields:
$first = true;
$sql = "select * from ajax_search where";
foreach ($search_words as $word) {
foreach ($columns as $col) {
$sql .= (($first) ? " " : " OR") . "`$col` LIKE \"%" . $word . "%\"";
$first = false;
}
}
Then run this query.
Another and also a better solution would be more complicated word(tag) based indexing, because this can generate morbid queries when used with more words.
I have a table which looks something like the following (first row is columns):
|section | col1 | col2 |
|----------------------|
|bananas | val | val2 |
|----------------------|
|peaches | val | val2 |
With some code to check if a section value matches up with one of the values in an array:
$sectionscope = Array('bananas', 'apples');
$sections = mysql_query("SELECT section FROM table WHERE col1=val AND col2=val2");
if (mysql_num_rows($sections)) {
$i = 0;
while ($row = mysql_fetch_array($sections)) {
if (in_array($row[$i], $sectionscope)) {
$section = $sectionscope[array_search($row[$i], $sectionscope)];
$section_is_valid = 1;
}
$i++;
}
}
If I echo the output from the while loop using echo $row[$i], it gives me: bananas
Doing the select from PHPmyadmin works fine
Can you tell me what I'm doing wrong here?
Thanks,
SystemError
Why are you incrementing $i in the while loop. Your query will return two rows and when you loop through the results, you can access the section value using $row[0] each time.
while ($row = mysql_fetch_array($sections)) {
echo $row[0];
}
This will print bananas and peaches.
In your code, when you enter the while loop second time, you are trying to retrieve section value using $row[1] (since your $i has incremented to 1), which will be null since your query result only contains one column.