Format SQL result into array; access by key? [duplicate] - mysql

This question already has answers here:
fetch data primary key value as the index for the associative array
(2 answers)
Closed 4 years ago.
I have a table with items with a name and id. Here's some create table code:
CREATE TABLE items (
id INT,
name TEXT
);
INSERT INTO items VALUES
(1, "Flute"),
(2, "Guitar"),
(4, "Saxophone"),
(7, "Tuba"),
(5, "Xylophone"),
(14, "Triangle");
I want to perform a query on this grabbing all items:
$stmt = $db->prepare("
SELECT id, name FROM items
ORDER BY id ASC
");
$stmt->execute();
$items = $stmt->fetchAll(PDO::FETCH_ASSOC);
This creates an array that looks something like the below:
Array (
[0] => Array ([id] => 1, [name] => "Flute"),
[1] => Array ([id] => 2, [name] => "Guitar"),
...
[5] => Array ([id] => 14, [name] => "Triangle")
)
I want to access this array by key id. Something like:
echo $array["1"]; // "Flute"
echo $array["14"]; // "Triangle"
echo $array["7"]; // "Tuba"
Not necessarily exactly like the above, but in a way that I can print name from the array by using key id. Is something like this possible? To format the array created earlier.

You will need to create a new array and iterate over the old.
Something like:
$newArray = array();
foreach ($array as $item)
$newArray[$item['id']] = $item['name']

Related

PDO Mysql same query but insert to multiple users [duplicate]

This question already has answers here:
What is the best way to insert multiple rows in PHP PDO MYSQL?
(4 answers)
Closed last year.
I would like through pdo insert multiple (bulk) rows with same value, only diffent is the user_id
I'm passing a array with userIds but i have no idea how to bind them.
<?php
require_once("db.php");
$usersId = $jsonData["usersId"];
$text = $jsonData["text"];
// Try to fetch the user from the database
$query = "INSERT INTO posts (user_id, text) VALUES (:usersId, :text)";
$stmt = $db->prepare($query);
// Bind value
$stmt->bindValue(":userId", $userId);
$stmt->bindValue(":text", $text, PDO::PARAM_STR);
// Execute
$result = $stmt->execute();
?>
My Tables:
CREATE TABLE users(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255)
);
INSERT INTO users (name)
VALUES ("Gregor"),
("Liza"),
("Matt"),
("Bob");
CREATE TABLE posts(
id INT PRIMARY KEY AUTO_INCREMENT,
user_id INT,
text VARCHAR(255)
);
You need a loop:
require_once("db.php");
$text = $jsonData["text"];
// Try to fetch the user from the database
$query = "INSERT INTO posts (user_id, text) VALUES (:usersId, :text)";
$stmt = $db->prepare($query);
// Bind value
$stmt->bindParam(":userId", $userId);
$stmt->bindValue(":text", $text, PDO::PARAM_STR);
// Execute
foreach ($jsonData["usersId"] as $userId) {
$result = $stmt->execute();
}
Use bindParam() so it binds to a reference to the variable. That allows you to reassign the variable each time through the loop without re-binding.

Yii2 getting columns name from SQL command when result == null

If you get the following code :
$DBConnection =
CreateNewDBConnection(Yii::$app->get('db_cdh'),$aDatabaseName);
$DBConnection->open();
$command = $DBConnection->createCommand($aQuery);
$queryres = $command->queryAll();
If there is result from the query, I get an array, like this
Array
(
[0] => Array
(
[name] => 2.6.084.545
[xdim+2] => 70
)
[1] => Array
(
[name] => 2.5.102.030
[xdim+2] => 60
)
[2] => Array
(
[name] => 2.5.141.560
[xdim+2] => 80
)
)
But if the result of the query is empty, i get an empty array.
How is it possible to get the columns name ?
The reason why I'm asking this, it's because I'm asking queries to multiple DBs and some have results (1 or more lines) and otherd not. The system almost works, but the grid view parse only the first line to find the columns to display. So depending on the order result across the multiple DB, the grid view display the columns or not, depending what come first ....
Any help welcome.
You can take the column names using yii\db\TableSchema and use them afterwards:
$columns = [];
if (empty($queryres)) {
$columns = $DBConnection->getTableSchema('your_table_name')->getColumnNames();
}

how to iterate values in php from arraylist to be display inside the html table

I am able to get the values from my Database table in the array form.
But i do not know how to print those values in my <table><tr><td>// values of subjectId comes here </td>
<td>//values of subject Name comes here</td></tr></table>. I want to iterate all the fields values one by one in my tag.
In Array i am getting values like this:
FIctionNon FIctionArray ( [0] => stdClass Object ( [subject_id] => 1 [subject_name] => FIction [creater_id] => 1 [created_date] => 2012-10-07 16:49:12 [update_id] => 1 [updated_date] => 2012-10-07 16:49:12 ) [1] => stdClass Object ( [subject_id] => 2 [subject_name] => Non FIction [creater_id] => 1 [created_date] => 2012-10-07 16:49:12 [update_id] => 1 [updated_date] => 2012-10-07 16:49:12 ) )
And my code for getting output is as follows:
$con = new connection();
$info = new Subdetails_setup($con);
$results = $info->getSubjectInfo();
print_r($results);
And my Method look like this:
function getSubjectInfo()
{
$sub_info = $this->con->prepare("SELECT * FROM subjectdetails");
$sub_info->execute();
$results = $sub_info->fetchAll(PDO::FETCH_OBJ);
foreach ($results as $key)
{
echo $key->subject_name;
}
// Return the result array
return $results;
}
My table is. "Subjectdetails"
subject_id int(3) NO PRI NULL auto_increment
subject_name varchar(150) NO NULL
creater_id int(5) NO NULL
created_date datetime NO NULL
update_id int(5) NO NULL
updated_date datetime NO NULL
.
Please help me for this.
To split apart your arrayed values, couldn't you use the explode function? I'm unfamiliar with it so I wouldn't be able to help with that. But, could you go about collecting your values, and echoing them a different way? Like shown below
$query = mysql_query("SELECT * from subjectdetails ORDER BY `subject_id` DESC ");
while($row = mysql_fetch_array($query)){
$subjectid = $row['subject_id'];
$subjectname = $row['subject_name'];
(The rest of your values here)
echo "
<table><tr><td>$subjectid</td> <td>$subjectname</td></tr></table>
";
}
I did not test that, but it should work.

add values with 'on duplicate key'

I have the folowing array called $words
Array
(
[0] => Array
(
[token] => dwA
[pos] => *DII.7,8*
)
[1] => Array
(
[token] => nTr
[pos] => *DI.5,9*
)
[2] => Array
(
[token] => dwA
[pos] => *DI.2,8*
)
[3] => Array
(
[token] => nTr
[pos] => *DI.2,8*
))
I want to insert it with the following :
foreach ($words as $value)
{
$word = $value['token'];
$attestation = $value['pos'];
$insert="INSERT INTO Examples (Word, Attestation) VALUES ('$word', '$attestation')
mysql_query($insert) OR die(mysql_error());
}
The table 'Examples' has a key called ID with auto increasement;
the field word is 'unique'
what I want is that in the field 'Attestation' the values are added each time the 'word' is the same
so the result should be the following:
Id word Attestation
1 dwA *DII.7,8*, *DI.2,8*
2 nTr *DI.5,9*, *DI.2,8*
so I tried to add a 'on duplicate key' phrase
foreach ($words as $value)
{
$word = $value['token'];
$attestation = $value['pos'];
$insert="INSERT INTO Words2 (Word, Attestation) VALUES ('$word', '$attestation')
on duplicate key update Attestation =
";
mysql_query($insert) OR die(mysql_error());
}
but I can't figure out what I have to add after Attestation = so that the differents attestations are added one after the other, like for example : DI.5,9, DI.2,8
Or is the 'on duplicate key' not the correct way to do this?
Try this;
INSERT INTO Words2 (Word, Attestation) VALUES ('$word', '$attestation')
on duplicate key update Attestation = CONCAT(Attestation, ', ', '$attestation')
Although, it may a bit difficult to break those values apart later on. You may want to consider another table, so you can set up a one-to-many relationship.

CI: Querying two tables in the model, explode

i'm thinking about this for days now and don't come to grasps (since i'm relativley new to MVC and CI). I'm not even sure whether this is an issue with MVC, MySQL or arrays.
Situation: 2 MySQL tables
Table data: id, title, list
Table values: id, name
Querying the data table results in an array like the following (excerpt):
[4] => Array
(
[id] => 3
[title] => Foo
[list] => 1,2,3,4,6,14
)
[5] => Array
(
[id] => 4
[title] => Bar
[list] => 2,6,9,12
)
The field list contains comma separated values that correspond to some IDs of the values table like
[3] => Array
(
[id] => 12
[name] => 'value12'
)
What I try to do for each row is:
take the list-values & explode it into an array
check with the result set from the values-table (via in_array() method)
return the name values of the IDs if
include it somehow into the main result set (e.g. as a 2-dimensional array):
[5] => Array (
[id] => 4
[title] => Bar
[list] => Array (
[0] => value6
[1] => value12
...
)
)
My naive approach so far was to
run a query on each of the 2 tables
compare the 2 result sets via in_array
My main problem (while trying to strictly separate model, controller and view): How can I include the name field from the values-table in the "main loop" of the data table result set?
if($q->num_rows() > 0)
{
$data[] = $q->result_array();
foreach ($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
If I use the following (cumbersome) approach i naturally get a new item each time:
foreach ($q->result_array() as $row)
{
$data[]['id'] = $row['id'];
$data[]['title'] = $row['title'];
$data[]['list'] = $row['year'];
}
Since this is a MySQL database I see no way to do the explode and the comparison in SQL (with LIKE or something else).
Any hint, even a simple link to an info bit, is highly appreciated.
Thanks a trillion!
fab
There is a many-to-many relationship between lists and list values. The conventional way to model this in a relational database is to create a joining table. So I'd structure your schema like this.
lists : list_id, title
values : value_id, name
list_values : list_id, value_id
list_values is the joining table. It links lists with values.
To build a list you could have the following functions in your model
function build_list($list_id)
{
$list = $this->get_list($list_id);
$list->values = $this->get_list_values($list_id);
return $list;
}
function get_list($list_id)
{
$sql = 'select * from lists where list_id=?';
return $this->db->query($sql, array($list_id))->row();
}
function get_list_values($list_id)
{
$sql = 'select v.value_id, v.name
from list_values lv
join values v on v.value_id=lv.value_id
where lv.list_id=?';
return $this->db->query($sql, array($list_id))->result();
}