Can I create an array by use php variable in a loop ?
<?php
for($i=5;$i<=100;$i++)
{
$sql = "SELECT * FROM users WHERE id = '$i' order by id asc";
$result = mysql_query($sql);
$datas=mysql_fetch_array($result);{
$username = stripslashes(str_replace('\r\n', '<br>',($datas['username'])));
}
${'name' . $i} = $username;
}
?>
Okay , Now I have php variable $name1-$name100
And then I want to create array by use php variable $name1-$name100
$my_array = array(php variable $name1-$name100);
How can I do ?
Just modify how you store the username:
$my_array = array();
for ( $i = 5; $i <= 100; $i++ ) {
$sql = "SELECT * FROM users WHERE id = '$i' order by id asc";
$result = mysql_query($sql);
$datas = mysql_fetch_array($result);
$username = stripslashes(str_replace('\r\n', '<br>',($datas['username'])));
$my_array[] = $username; // push usernames into array
}
Also you shouldn't run so many queries, so I suggest something like this:
$usernames = array();
$query = "SELECT * FROM users WHERE id >= 5 AND id <= 100 ORDER BY id ASC";
$result = mysql_query( $query );
if ( mysql_num_rows( $result ) > 0 ) {
while ( $data = mysql_fetch_assoc( $result ) )
$usernames[] = stripslashes( str_replace( '\r\n', '<br>', $data['username'] ) );
}
Related
I'm trying to select values from database where date is equal to random date and sometimes there is no records how can I run the select again with another random value without refreshing website?
$start = "2017-08-12";
$now = date("Y-m-d");
$now = date('Y-m-d', strtotime($now. ' - 7 days'));
$daty = array();
while($start<$now){
$start = date('Y-m-d', strtotime($start. ' + 7 days'));
$daty[] = $start;
}
$rand_keys = array_rand($daty, 2);
$random_data = $daty[$rand_keys[0]] ;
$sql2= 'SELECT count(*) as total from tab where
Date="'.$random_data.'"';
$result12 = mysqli_query( $conn, $sql2 );
$row12 = $result12->fetch_assoc();
if($row12>0){
$sql1 = 'select * from premier1718 where Date="'.$random_data.'"';
$result1 = mysqli_query( $conn, $sql1 );
while($row1 = $result1->fetch_assoc()){
echo $row1["HomeTeam"]." ".$row1["AwayTeam"]."</br>";
}
I think you can possibly do this in one query like this
$sql = 'select * from `premier1718` where `date`=(
select `date` from `tab` where `date` in ( "'.implode( '","', $daty ).'" ) order by rand() limit 1
)';
$result = mysqli_query( $conn, $sql );
if( $result ){
while( $rs=$result->fetch_object() ) printf('%s %s<br />',$rs->hometeam,$rs->awayteam);
}
$rand_keys = array_rand($daty, 2);
$random_data = $daty[$rand_keys[0]] ;
$sql2= 'SELECT count(*) as total from tab where
Date="'.$random_data.'"';
$result12 = mysqli_query( $conn, $sql2 );
$row12 = $result12->fetch_assoc();
if($row12>0){
$success = false;
while ($success == false) {
$sql1 = 'select * from premier1718 where Date="'.$random_data.'"';
$result1 = mysqli_query( $conn, $sql1 );
while($row1 = $result1->fetch_assoc()){
$success = true;
echo $row1["HomeTeam"]." ".$row1["AwayTeam"]."</br>";
}
}
Currently I'm working on a project, which using the depth first search to retrieve value, but I'm only able to echo the value, but I don't know how to store the value into the variable.
Here is my code
function calculate_ttl_member_agent ($conn, $id) {
$id_val = $level = "";
$search_dl_sql = "select * from table where foreign_ID = ".$id;
$search_dl_exe = mysqli_query($conn, $search_dl_sql);
while($result = mysqli_fetch_assoc($search_dl_exe)) {
$level = $result['level'];
$id_val = $result['ID'];
echo ",'".$level."'";
calculate_ttl_member_agent ($conn, $id_val);
}
}
I have been trying the use return, but it only give the first level value..
Create an array and add values to it.
function calculate_ttl_member_agent ($conn, $id) {
$id_val = $level = "";
$search_dl_sql = "select * from table where foreign_ID = ".$id;
$search_dl_exe = mysqli_query($conn, $search_dl_sql);
// define an empty array
$arr = [];
while($result = mysqli_fetch_assoc($search_dl_exe)){
$level = $result['level'];
$id_val = $result['ID'];
echo ",'".$level."'";
calculate_ttl_member_agent ($conn, $id_val);
array_push( $arr, [$level, $id_val, 'add anything else needed']);
return $arr;
}}
Store values in an array as commented by Alexanderp and use after
// inside while
$level = $result['level'];
$id_val = $result['ID'];
$level[]= $level;
or
$arr['level'][] = $result['level'];
$arr['id_val'][] = $result['ID'];
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));
Following is my PHP code which is only giving i =0 though in a loop I am incrementing the $i but it always return i as 0 and while loop is only working one time, though my query SELECT * FROM events WHERE DATE(event_date) < CURDATE() is returning 7 records when exectuing in phpmyadmin. Let me know what i am doing wrong here ?
Code -
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/app/'."config.php";
error_reporting(E_ALL);
if( $_POST['number'] == 'all' ) {
$eventArr = array();
$myarray = array();
$query = "SELECT * FROM events WHERE DATE(`event_date`) < CURDATE()";
$result = mysql_query($query);
$i =0;
while($row = mysql_fetch_assoc($result)) {
$eventArr[$i] = array('event_data'=> $row);
// Get image For an event
$event_id = $row['id'];
$query = "SELECT * FROM event_images WHERE event_id = $event_id ORDER BY `uploaded_date` DESC LIMIT 0,1";
$result = mysql_query($query);
$eventImgArr = array();
while($row = mysql_fetch_assoc($result)) {
$eventImgArr[] = $row;
}
$eventArr[$i]['event_image'] = $eventImgArr;
// Get venue details for the event
$venue_id = $row['venue_id'];
$eventVenArr = array();
$query = "SELECT * FROM `venues` WHERE id = $venue_id";
while($row = mysql_fetch_assoc($result)) {
$eventVenArr[] = $row;
}
$eventArr[$i]['venue_detail'] = $eventVenArr;
echo $i, " -- ";
$i++;
}
$myarray = array('response'=>'1','message'=>'Event data', 'data'=>$eventArr);
echo json_encode($myarray);
return;
}
You are re-using the $result variable for the other queries, which is destroying its value needed for the main loop.
P.S. Also, you're not actually executing the query for the venue details.
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
}