How can I make this array with data from a database?
$array=array("a"=>"Apple","b"=>"Ball","c"=>"Cat");
I have a database table with column letter and value.
letter | value
|
a | Apple
b | Ball
c | Cat
I want "a"=>"Apple","b"=>"Ball","c"=>"Cat" to be values from the database, using for loop, how is that possible?
Many thanks for any help!
assuming you can do the connection and select
$array=array();
while ($row = mysql_fetch_assoc($result)) {
$array[$row['letter']]=$row['value'];
}
print_r($array);
Related
I have two rows of data - always just two rows, but there could be a maximum of around forty columns. The column names are different on a case by case basis, but here is a representative example:
id | height | width | colour | in_stock | featured | on_sale
------------------------------------------------------------
1 | 30 | 20 | black | yes | no | yes
2 | 30 | 25 | red | yes | yes | no
I want to get all of the differences between those two rows into an array so that I can log what was changed from row 1 to row 2.
I thought it array_diff() would do the job!
So I cheerfully chucked array_diff() at it thus:
//Simplified queries for the example
$sql1 = "SELECT * FROM table WHERE id = 1";
$rs1 = $conn->Execute($sql1);
$rs1 = $rs1->fields;
$sql2 = "SELECT * FROM table WHERE id = 2";
$rs2 = $conn->Execute($sql2);
$rs2 = $rs2->fields;
//Build first array
foreach($rs1 as $key => $value){
$data1[$key] = $value;
}
//Build second array
foreach($rs2 as $key => $value){
$data2[$key] = $value;
}
//Find the differences
$theDifferences = array_diff($data1, $data2);
//Loop through the differences logging the changes
foreach($theDifferences as $field => $value){
echo "Change found for ".$field."!";
}
Why that doesn't work.
This "looked like" it was working. Since many columns contain long strings, colour names, dates etc, so when one changed it was duly pushed into the differences array. The problem was (of course) that the multiple "yes" or "no" columns did not behave as I had expected. Thus the result of the code above, for the table example is:
colour, width
It is not "seeing" the featured or on_sale columns as changed because the data1 array AND the data2 array both contain no's and yes's.
I suppose I need to compare on a key by key basis? Something like the opposite of array_diff_key()? But here I am stuck.
I also considered if this could be done solely with the SQL query, which would I suppose be more efficient, but that is way beyond my SQL ability.
Thanks in advance.
I think you're very nearly there. Maybe something like this after your queries:
$theDifferences = array();
foreach($rs1 as $key => $value){
if ($rs2[$key] != $value){
$theDifferences[$key] = $value;
}
}
As for SQL, you can use an EXCEPT to get a list of rows which are different between two queries, but you'd still have to loop through the keys and look for nulls - which doesn't save you a whole lot.
I have a MySQL Table which is structured like so:
key ID value1 value2
| 1 | | ID1 | |2| |4|
| 2 | | ID2 | |5| |5|
.
.
.
I need to query this table and return just the IDs based on ascending order of the difference between value1 and value 2. If there are equal values then the ID order is irrelevant and can be random. The format of the output is important though. It should be a long string separated by the shown tokenizer. I have:
$query = "Select * From `Table`";
$result = $conn->query($query),
while($row = $result->fetch_assoc()) {
code???
echo $row["ID"]."!##$";
}
How can I structure the missing code block to accomplish this? I think what I want to do is create a variable which is (value1 - value2) then create an array which stores the id as a key with the result and sort ascending then echo the key. I just don't know how to write it
Have a look at this - PHP MySQL Multi Query
I have 600 rows of data in one table and table structure is,
Table Name: city_Data
------------------------------
cityId | cityName
------------------------------
1 | chennai
2 | madurai
3 | trichy
4 | kovai
...
...
...
------------------------------
cityId - autoincrement
now i would like to mix this table data and inset into another table. this table's name is city_Mix.
---------------------------------------
mixId | city1 | city2
---------------------------------------
1 | chennai | madurai
2 | chennai | trichy
3 | chennai | kovai
4 | madurai | chennai
5 | madurai | trichy
6 | madurai | kovai
7 | trichy | chennai
...
...
...
---------------------------------------
here, city1 and city2 are should not be same and mixId - autoincrement
how to do this? anyone plz help me with sample code..
try the following query, which uses join to combine the city names which dont match and insert the dat to city_mix table
INSERT INTO city_mix
(city1,city2) select t1.cityName,t2.cityName from Table1 t1 join Table1 t2 on t1.cityName != t2.cityName;
http://sqlfiddle.com/#!9/2e01ea/3
I'm making some assumptions about what you are specifically asking, if you were to supply a little more information it might help:
Does city_Mix already contain the field city2 or is that the column you wish to join from city_Data?
Are you doing this in PHP or SQL?
Is city_Mix really a self-iteration of the city_Data table?
Is the data you've presented representational of a database table, or a PHP data structure?
Once again, I am making some assumptions here, but I'll try to help based on what you've provided...
It appears that city_Mix matches #3 from my question list (so you want to take a list of items, and for each item in the list, map it to all other items on the list). If this assumption is correct, here is one way to approach the solution:
Using SQL
// You'll probably want to use an INNER JOIN to accomplish this quickly, something like the following
(SELECT 'cityName' FROM `city_Data` c INNER_JOIN `city_Data` m ON m.cityName != c.cityName)
Using PHP
FYI: I would recommend against this in favor of doing this with SQL, but wanted to provide it as "a way to do it" since you did not indicate which way you were approaching the solution.
<?php
$cityMixData = []; //Final data table as you've indicated you desire
//Connect to your database
$con = mysql_connect("localhost","inmoti6_myuser","mypassword");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("databaseName", $con);
// Define our SQL query
$query = "SELECT DISTINCT `cityName` FROM `city_Data` ORDER BY `cityId`";
// Execute the query
$cities = mysql_query($query);
$i = 1; // Iterator index
$cityMixData = [];
// Loop through the list of unique city names and map all other items accordingly
while( $city = mysql_fetch_array( $cities, MYSQL_ASSOC ) ) {
$tmpArr = $cities;
unset($tmpArr[$row[$i - 1]); // Remove self
$cityMap = array_values($tmpArr); // reindex array
$mixRow = array($mixId => $i, $city1 => $city['cityName'], $city2 => $cityMap); // Create a row with auto-increment ID, city1 === unique city name, city2 === list of unique cities sans-city1
$cityMixData[] = $mixRow; // Add row to cityMixData which is multi-dimensional array
$i++; // Increment iterator
}
// Connect to DB
// Create city_Mix table if not exist
// Appropriately generate SQL based on $cityMixData structure, might get messy
// Save to DB
?>
If you answer the questions I posed above, I will be able to help more.
I need your help with display of some comma separated enteries from my database.
My main table schema looks like this
|---|----------|-----------|----------------------------|
|id | tab1 | tab2 | tab3 |
|---|----------|-----------|----------------------------|
|1 | state1 | A-North | constA1,constA2,constA3 |
|2 | state2 | B-South | constB1,constB2,constB3 |
---------------------------------------------------------
Query I'm trying to make work
$query = mysql_query("SELECT * FROM `main` WHERE `tab1` = '$tab1'")
or die(mysql_error());
while($row=mysql_fetch_array($query)){
$tab3 = explode(",", $row['tab3']);
echo $tab3."<br>";
}
What I want to display from the database
A-North B-South
---------------------
constA1 constB1
constA2 constB2
constA3 constB3
Error I'm getting when I run that query is "Array" . When I run the same code from phpMyAdmin, I get the desired rows (result).
Explode gives you the results in an array so you'll want another loop that runs through the $tab3 array printing the result. See the definition from the PHP manual:
Returns an array of strings, each of which is a substring of string
formed by splitting it on boundaries formed by the string delimiter.
For example:
for ($i = 0; $i < sizeof($tab3); $i++) {
echo $tab3[$i].'<br />';
}
explode will return array using print_r($tab3) you can view the items and access it by
echo $tab[0];
echo $tab[1];
echo $tab[2];
etc.....
explode ($separator,$string) returns an array. You need to step through the array to create the table columns.
Also, as you want the data in two columns, create these separately as two separate tables and then include those into a single table as two separate cells
Finally, redesign your database table. You'll thank us in the end
id | title | text
1 | aa |
2 | aa |
3 | aa |
I have some data from json data, i am not sure how many datas have duplicate in it.
$json = '[{"a":"1","b":"bb"},{"a":"2","b":"cc"},{"a":"3","b":"bb"}]';
$array = json_decode($json);
foreach($array as $key){
UPDATE table SET text = '".$key->b."' WHERE id = '".$key->a."' and title='aa'");
}
For example, as this situation, $key->b has 2 data bb from the json data, I only want update the first one and check if bb has already in the database, then ignore update.
id | title | text
1 | aa | bb
2 | aa | cc
3 | aa | <-ignore updtae, left the data empty
I know there have an easy way, first select * from table where text != '$key->a' for check, but this will cost 2 mysql query and make one more foreach, so
how to use one mysql query, update data without duplicate?
many thanks.
If your database is MySQL, maybe you can use the ON DUPLICATE KEY UPDATE.
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
I suggest using an array to store all the values of b you have used so far and only run the UPDATE if the value didn't exist yet.
$json = '[{"a":"1","b":"bb"},{"a":"2","b":"cc"},{"a":"3","b":"bb"}]';
$usedValues = array();
$array = json_decode($json);
foreach($array as $key){
if(!isset(usedValues[$key->b])) {
mysql_query("UPDATE table SET text = '".$key->b."' WHERE id = '".$key->a."' and title='aa'");
usedValues[$key->b] = true;
}
}
EDIT: If your database already has values for text this may still produce duplicates, but you could do a SELECT DISTINCT ´text´ and populate the $usedValues array with them.