$thearray = array
(
//(0)ID, (1)NAME, (2)LOCATION, (3)PHONE
array("0","Name 1","Nowhere 11","0004444"),
array("1","Name 2","Everywhere 11","0005555"),
array("2","Name 3","ThisPlace 11","0002222"),
array("3","Name 4","NoPlace 11","0003333"),
array("4","Name 5","ThatPlace 11","0001111")
);
This is how I used to store my information
I would then run through them to find what I needed
and display them using for example
echo $thearray[$i][4]
I want to do the same thing except store that information in Mysql
This is how far I've gotten but I keep getting strange errors and I cant output from the array
This is how far I've gotten
$result = $db->query("SELECT * FROM table");
$thearray = array();
while($thearray = $result->fetch_assoc()){
$thearray[] = $thearray;
}
For some reason this isn't working for me, its like it isnt in a 2d array like I have above :S I can't simply echo it like I did before.
Well first of all
while($thearray = $result->fetch_assoc()){
$thearray[] = $thearray;
}
Will keep overwriting the array and get very confused
try
while($row = $result->fetch_assoc()){
$thearray[] = $row;
}
The array returned from your query is no longer a simple array, it is a associative array
i.e. it will look something like this:
$new_array = array
(
//(0)ID, (1)NAME, (2)LOCATION, (3)PHONE
array('ID' => "0", 'NAME' => "Name 1", 'LOCATION' => "Nowhere 11", 'PHONE' => "0004444"),
array('ID' => "1", 'NAME' => "Name 2", 'LOCATION' => "Nowhere 22", 'PHONE' => "0005555"),
etc
);
So now when you want to use it you will have to use this sort of construct
$name = $new_array[$i]['NAME']
$location = $new_array[$i]['LOCATION']
etc
or
<?php echo $new_array[$i]['NAME']; ?>
<?php echo $new_array[$i]['LOCATION'] ?>
etc
Related
I want three element in associative array, so far am successful in getting two in the array.
$sql = "SELECT * FROM `notification_table` ";
$resultsd1 = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($resultsd1);
$associativeArray = array();
while ($row = mysqli_fetch_assoc($resultsd1))
{
$associativeArray[$row['name']] = $row['price'] ;
}
foreach($associativeArray as $k => $id){
echo $k."=>".$id .' ';
}
And am getting the response like this
name1=>24.725 name2=>24.265
Now i want to add another column in array as well and the name is column is notification_check .
Am not able to get how to add three columns in a single array. Any help will be appreciated.
I want the output like name1=>24.725=>yes_notification name2=>25.43=>no_notification
And when i print_r($row) is show this output Array ( [sno] => 1 [name] => name1 [price] => 23 [notification_check] => yes_notification)
You could shorten this and use mysqli_fetch_all to create an array of all of the data and then manipulate the array using array_column to create the index...
$result = mysqli_fetch_all($resultsd1, MYSQLI_ASSOC);
$associativeArray = array_column($result, null, 'name');
I am querying MySQL to perform an operation and return an array. To do this I am using the following code:
$return_array = array(
"title" => "nearby media",
"nearby_media_list" => array()
);
$my_query = "select * from `Media`";
$result = $conn->query($my_query);
while($row = $result->fetch_assoc()) {
$mediaLat = $row["lat"];
$mediaLon = $row["lon"];
$calculated_distance = distance( $userLat, $userLon, $mediaLat, $mediaLon, "M");
if( $calculated_distance <= $distance_limit ) {
// Build array
$return_array["nearby_media_list"][] = array(
'uid' => $row['uid']
);
}
}
echo json_encode($return_array);
$conn->close();
?>
and my output looks like this:
{"title":"nearby media","nearby_media_list":[{"uid":"-Kn1f0jo_36qnQBCqjCq"}]}
Since the array only contains one type of data I don't need to store a key and don't need JSON. What I want is a simple array of the values separated by a token so I can take it apart more easily. desired outcome is something like
[value1##$%value2##$%]
Can anyone instruct me how to do this? I haven't had any luck
I'm using JSON_encode to send data to a js file for tracks. A user could have one or several tracks so that's where the problem lies. Not sure how to organise my array to allow for several arrays. I can't use an array within an array since all the JSON data needs to be separated preferably so there will be something like;
track1 {ID:110232....}
track2 {ID:21402....}
What I have now works fine if there is just one track.
$ID = $_GET['ID'];
$result = mysql_query("SELECT * FROM tracks WHERE ID = '$ID' ORDER BY timestamp DESC");
while($row = mysql_fetch_array($result)){
$T_ID = $row['T_ID'];
$T_url = $row['url'];
$T_name = $row['name'];
$T_timestamp = $row['timestamp'];
$arr = array('T_ID' => $ID,'T_name' => $T_name, 'T_url' => $T_url, 'T_timestamp' => $T_timestamp );
echo json_encode($arr);
}
Why can't you use an (associative) array inside an container array like this:
$cont = array();
while($row = mysql_fetch_array($result)){
$T_ID = $row['T_ID'];
$T_url = $row['url'];
$T_name = $row['name'];
$T_timestamp = $row['timestamp'];
$arr = array('T_ID' => $ID,'T_name' => $T_name, 'T_url' => $T_url, 'T_timestamp' => $T_timestamp );
$cont[] = $arr;
}
echo json_encode($cont);
This results in a JSON structure like this, which keeps all your tracks in separate objects:
[
{'T_ID': 1, 'T_name': 1, ... },
{'T_ID': 2, 'T_name': 2, ... },
{'T_ID': 3, 'T_name': 3, ... },
...
]
As noted in the comments you should switch to PDO or mysqli- functions, but this doesn't matter for the problem at hand..
This is a problem that I come across frequently when using PHP to query mysql data, and I would like to know if there is a more efficient solution. When I only need two columns of data, for instance the columns 'id' and 'price', I prefer this 'flat' format:
array(
id 1 => price 1,
id 2 => price 2,
id 3 => price 3,
...
);
or in json:
[{"id 1":"price 1"},{"id 2":"price 2"},{"id 3":"price 3"}, ...]
And my usual solution is to loop twice, like so:
require_once('server/connection.php');
$info = mysql_query("SELECT id, price FROM table");
$array1 = array();
while ($row = mysql_fetch_assoc($info)) {
$array1[] = array(
'id' => $row['id'],
'price' => $row['price']
);
}
mysql_close($con);
$array2 = array();
foreach ($array1 as $key => $value) {
$array2[$key][$value['id']] = $value['price'];
}
print json_encode($array2);
which does work, but I think this code is too lengthy for its purpose, and there should be a better way -- so that I only have to loop one array. Any suggestions?
You can simplify your loop to this
while ($row = mysql_fetch_assoc($info)) {
$array1[] = array(
'id '.$row['id'] => 'price '.$row['price']
);
}
print json_encode($array1);
$result = array();
while ($row = mysql_fetch_assoc($info)) {
$result[$row['id']] = $row['price'];
}
print_r($result);
require_once('server/connection.php');
$info = mysql_query("SELECT id, price FROM table");
$array1 = array();
while ($row = mysql_fetch_assoc($info))
$array1[$row['id']] = $row['price'];
mysql_close($con);
print json_encode($array1);
NOTE: your $array2 is a two dimensional array. If it works for you, you need to change your javascript code to handle following flat format i.e. the above code produce
[{"id 1":"price 1"},{"id 2":"price 2"},{"id 3":"price 3"}, ...]
I got a database with 2 fields: amount and name.
I want to get all the data from the database (40 rows) and create an associated array out of it like this:
$arr = array("amount" => "12", "name" => "John");
How is this done dynamically in PHP? I am stuck.
If you're using the mysql_* function, you can do the following to get one row at a time:
$res = mysql_query("SELECT amount, name FROM mytable");
while ($row = mysql_fetch_assoc($res)) {
var_export($row); // outputs array ( 'amount' => '12', 'name' => 'John', )
}
To get all rows in a single array:
$customers = array();
$res = mysql_query("SELECT amount, name FROM customers");
while ($row = mysql_fetch_assoc($res)) {
$customers[] = $row;
}
Well, if you run your query, e.g.
$result = mysql_query('SELECT amount, name FROM table');
you can loop over the result like that:
$values = array();
while(($row = mysql_fetch_assoc($result))) {
$values[] = $row;//$row will be like array("amount" => "12", "name" => "John")
}
and you will have an array of arrays.
Check out mysql_fetch_assoc if you want to fetch database rows as an associative array (the documentation comes with a good example, too).
$data = $pdo->query('SELECT amount, name FROM ...')->fetchAll(PDO::FETCH_ASSOC);
That's it in PDO. And if you're not using PDO, well, that's your problem then...