I have this piece of code:
Tipo_Id = mysql_real_escape_string($_REQUEST["tipo"]);
$Sql = "SELECT DISTINCT(tabveiculos.Marca_Id), tabmarcas.Marca_Nome
FROM tabmarcas, tabveiculos
WHERE tabmarcas.Tipo_Id = '$Tipo_Id'
AND tabmarcas.Marca_Id = tabveiculos.Marca_Id
ORDER BY tabmarcas.Marca_Nome Asc";
$Query = mysql_query($Sql,$Conn) or die(mysql_error($Conn));
$marcas = array();
while ($Rs = mysql_fetch_array($Query)) {
$marcas[] = array(
$Rs['Marca_Id'] =>
$Rs['Marca_Nome']
);
}
echo ( json_encode($marcas) );
this returns a result like this:
[{"2":"Chevrolet"},{"7":"Citro"},{"4":"Fiat"},{"3":"Ford"},{"6":"Peugeot"},{"1":"Volkswagen"}]
so how i can change to returns like this:
{"2":"Chevrolet","7":"Citro","4":"Fiat","3":"Ford","6":"Peugeot","1":"Volkswagen"}
You're currently creating a new array for each key value pair, hence, ending up with a multidimensional array. Do the following instead.
while ($Rs = mysql_fetch_array($Query)) {
$marcas[ $Rs['Marca_Id'] ] = $Rs['Marca_Nome'];
}
Related
PROBLEM
I have a set of data that is being output by selecting each dataset and utputting them row by row.
QUESTION
Is there a method of fetching this data and storing it as an array that I am then able to out turn into set of string values?
$sql = "SELECT * FROM respondent_data WHERE respondent_firstname = 'John'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$categoriesTest[] = $row["respondent_sdo"];
$row["respondent_dcto"];
$row["respondent_ed"];
$row["respondent_ca"];
$row["respondent_dhpt"];
$row["respondent_irt"];
$row["respondent_gl"];
$row["respondent_il"];
// Turn my output into an array ready to be used for the JSON string
}
}
EXAMPLE
So each of those values outputs an integer from the column rows I need them to be turned into an array like: 2,4,3,5....
If you only want specific associative properties from all columns queried from the MySQL call, just set them in an array with their respective properties:
$categoriesTest = array();
$sql = "SELECT * FROM `respondent_data` WHERE `respondent_firstname` = 'John'";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
$categoriesTest[] = array(
'respondent_sdo' => $row['respondent_sdo'],
'respondent_dcto' => $row['respondent_dcto'],
'respondent_ed' => $row['respondent_ed'],
'respondent_ca' => $row['respondent_ca'],
'respondent_dhpt' => $row['respondent_dhpt'],
'respondent_irt' => $row['respondent_irt'],
'respondent_gl' => $row['respondent_gl'],
'respondent_il' => $row['respondent_il']
);
}
$categoriesTest = json_encode($categoriesTest); // get JSON
However, if you wanted to keep all columns queried, but create custom elements you'll want to use array_merge:
$categoriesTest = array();
$sql = "SELECT * FROM `respondent_data` WHERE `respondent_firstname` = 'John'";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
$categoriesTest[] = array_merge($row, array(
'custom_value_1' => 'test',
'custom_value_2' => 'test2'
));
}
$categoriesTest = json_encode($categoriesTest); // get JSON
This should do the trick.
$sql = "SELECT * FROM respondent_data WHERE respondent_firstname = 'John'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$i=0;
while($row = mysqli_fetch_assoc($result)) {
$categoriesTest[$i]["respondent_sdo"] = $row["respondent_sdo"];
$categoriesTest[$i]["respondent_dcto"] = $row["respondent_dcto"];
$categoriesTest[$i]["respondent_ed"] = $row["respondent_ed"];
$categoriesTest[$i]["respondent_ca"] = $row["respondent_ca"];
$categoriesTest[$i]["respondent_dhpt"] = $row["respondent_dhpt"];
$categoriesTest[$i]["respondent_irt"] = $row["respondent_irt"];
$categoriesTest[$i]["respondent_gl"] = $row["respondent_gl"];
$categoriesTest[$i]["respondent_il"] = $row["respondent_il"];
$i++;
}
var_dump($categoriesTest);
}
I'm trying to get the result of a stored procedure in MySQL into an array with use of php. The code I have:
function get_all_uzovi($dbc) {
//$query = "SELECT diagnose_id, diagnose_code, specialisme_agb_code_fk
// FROM tbl_diagnoses
// WHERE specialisme_agb_code_fk = '$var_chosen_specialism'
// ORDER BY diagnose_code ASC";
$result = mysqli_query($dbc,"CALL spGetUzovi");
//WHAT DOES NOT WORK:
//$data = array();
//while ( $row = $result->fetch_assoc() ) {
// $data[] = $row;
//}
//return json_encode($data);
//WHAT DOES WORK:
while ($row = mysqli_fetch_array($result)){
echo $row[0] . " - " . + $row[1];
}
}
The code under "//WHAT DOES NOT WORK" is what I need: the result as a json format. For some reason it gives me nothing..
The code under "//WHAT DOES WORK", does work, but this is not what I want.
the code for the sp:
CREATE DEFINER=`ziekenh3`#`localhost` PROCEDURE `spGetUzovi`()
NO SQL
SELECT *
FROM tbl_uzovi
the code that I use when working with queries (which does work) instead of sp:
function get_diagnoses($dbc,$var_chosen_specialism) {
$query = "SELECT diagnose_id, diagnose_code, specialisme_agb_code_fk
FROM tbl_diagnoses
WHERE specialisme_agb_code_fk = '$var_chosen_specialism'
ORDER BY diagnose_code ASC";
$result = mysqli_query($dbc,$query);
$data = array();
//while ( $row = $result->fetch_assoc() ) {
while ( $row = mysqli_fetch_assoc($result) ) {
$data[] = $row;
}
return json_encode($data);
}
Any thoughts?
Does this work?
function get_all_uzovi($dbc) {
$result = mysqli_query($dbc,"CALL spGetUzovi");
$data = array();
while ( $row = $result->fetch_assoc() ) {
$data[] = $row;
}
return json_encode($data);
}
I Solved it. A bit of a stupid problem: there where some fields in the result set that contained characters like: , ( . etc. I don't think json likes this..
When I did a SELECT * FROM on another table it worked. So, my code that works now is:
function get_all_uzovi($dbc) {
$q = "CALL spGetUzovi";
$r = mysqli_query($dbc,$q);
while ($row = mysqli_fetch_assoc($r)) {
$data[] = $row;
}
return json_encode($data);
}
I'm sorry for the inconvenience!
i had this php code :
<?php
include "../mainmenu/koneksi.php";
// Start with the list of animals
$sql = "SELECT * FROM data_binatang";
$rows = array();
$res = mysql_query($sql);
for($i=0; $i<mysql_num_rows($res); ++$i){
$row1 = mysql_fetch_assoc($res);
$id_binatang = $row1['id_binatang'];
$sql = "SELECT * FROM data_waktu_vaksinasi WHERE id_binatang = $id_binatang AND (status_vaksin = 'belum' OR status_vaksin IS NULL) ORDER BY tanggal_vaksin ASC LIMIT 1";
$res2 = mysql_query($sql);
$row2 = mysql_fetch_assoc($res2);
$arr[$id_binatang] = array();
array_push($arr[$id_binatang], $row1['nama_binatang'], $row1['id_user'], $row1['jenis_binatang'], $row1['ras_binatang'], $row1['foto_binatang'], $row2['nama_vaksin'], $row2['id_data_waktu_vaksinasi'], $row2['status_vaksin'], $row2['tanggal_vaksin'], $row2['tanggal_datang']);
}
echo "RESULT:";
echo "<table border=1><tr><th>id binatang</th><th>nama binatang</th><th>id user</th><th>jenis binatang</th><th>ras binatang</th><th>foto binatang</th><th>nama vaksin</th><th>id data waktu vaksin</th><th>status vaksin</th><th>tanggal vaksin</th><th>tanggal datang</th></tr>";
foreach($arr as $key => $val){
echo "<tr><td>$key</td><td>".implode("</td><td>", $val)."</td></tr><br>";
}
?>
and here's the result
now i want to generate the table into json, but i don't know what to put inside the json encode, i tried:
echo '{"data_vaksinasi_menu":'.json_encode($arr[$id_binatang]).'}';
but instead it gave me null
Try this:
echo json_encode(array('data_vaksinasi_menu' => $arr));
MySql query returns me a multi-dimensional array :
function d4g_get_contributions_info($profile_id)
{
$query = "select * from contributions where `project_id` = $profile_id";
$row = mysql_query($query) or die("Error getting profile information , Reason : " . mysql_error());
$contributions = array();
if(!mysql_num_rows($row)) echo "No Contributors";
while($fetched = mysql_fetch_array($row, MYSQL_ASSOC))
{
$contributions[$cnt]['user_id'] = $fetched['user_id'];
$contributions[$cnt]['ammount'] = $fetched['ammount'];
$contributions[$cnt]['date'] = $fetched['date'];
$cnt++;
}
return $contributions;
}
Now I need to print the values in the page where I had called this function. How do I do that ?
change the function like this:
while($fetched = mysql_fetch_array($row, MYSQL_ASSOC))
{
$contributions[] = array('user_id' => $fetched['user_id'],
'ammount' => $fetched['ammount'],
'date' => $fetched['date']);
}
return $contributions;
Then try below:
$profile_id = 1; // sample id
$result = d4g_get_contributions_info($profile_id);
foreach($result as $row){
$user_id = $row['user_id']
// Continue like this
}
I get an array of values returned from the following function:
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
I now want to use these values in a new function, where each "user_id" is used to collect text from the database through this function:
function get_text($writer) {
$writer = mysql_real_escape_string ($writer);
$sql = "SELECT * FROM `text` WHERE user_id='$writer' ORDER BY timestamp desc";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
However the returned value from the first function is an array, and as I've learnt the hard way, arrays cannot be treated by "mysql_real_escape_string".
How can I make the second function handle the values that I got from the first function?
Any responses appreciated.
Thank you in advance.
Your first mistake is to use mysql_fetch_assoc when only selecting one column. You should use mysql_fetch_row for this. This is likely going to fix your primary problem.
Could look like this:
$subs = get_subscribitions($whateverId);
$texts = get_text($subs);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_row($result)) {
$user_id = $row['user_id'];
$rows[$user_id] = $user_id;
}
mysql_free_result($result);
return $rows;
}
function get_text($writer) {
$writers = implode(",", $writer);
$sql = "SELECT * FROM `text` WHERE user_id IN ({$writers}) ORDER BY timestamp DESC";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_array($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
}
This will save you a lot of time, because you can get all data from 'text' in one statement.
The solution is to avoid placing arrays in your $rows array in the first function. Instead of:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
try:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
This will place only the value from column 'user_id' in the $rows array.
In order to use the second function you must iterate over the array returned from the first one. Something like this could work for you:
$user_subscriptions = get_subscribitions($user);
foreach($user_subscriptions as $subscription) {
$texts = get_text($subscription['user_id']);
foreach($texts as $text) {
// do something with the fetched text
}
}
As George Cummins says,
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
and, to speed up the second function:
function get_text($writer)
{
$sql = "SELECT * FROM `text` WHERE user_id in (".implode(',',$writer).") ORDER BY timestamp desc";
$rows = array();
if ($result = mysql_query($sql))
{
while ($row = mysql_fetch_assoc($result))
{
$rows[] = $row;
}
mysql_free_result($result);
}
return $rows;
}
The change to the query means that you only do one in total rather than one for each ID thus removing the time taken to send the query to the server and get a response multiple times. Also, if the query fails, the function returns an empty array
Use :
string implode ( string $glue , array $pieces )
// example, elements separated by a comma :
$arrayasstring = impode(",", $myarray);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$row = mysql_fetch_row($results);
mysql_free_result($result);
return intval($row['user_id']);
}
it return only the user id you can used it in the 2nd function