I am trying to display a single row data using mysqli.
The query is
$getfield = mysqli_query($con,"select name from as_users where user_id=34");
if (mysqli_num_rows($getfield) > 0)
{
while($rowpwd = mysqli_fetch_array($getfield))
{
echo $rowpwd['name'];
}
}
if I print then i get
echo '<pre>';
print_r(mysqli_fetch_array($getfield));
echo '</pre>';
Array
(
[0] => abc
[name] => abc
)
But getting the name inside the while loop doesn't work.
Any help is highly appreciated.
Just try this:
$getfield = mysqli_query($con,"select name from as_users where user_id=34");
if (mysqli_num_rows($getfield) > 0)
{
$rowpwd = mysqli_fetch_array($getfield)['name'];
echo $rowpwd;
}
OR
$getfield = mysqli_query($con,"select name from as_users where user_id=34");
if (mysqli_num_rows($getfield) > 0)
{
$rowpwd = mysqli_fetch_array($getfield);
echo $rowpwd['name'];
}
Try this:
$getfield = mysqli_query($con,"select name from as_users where user_id=34");
if (mysqli_num_rows($getfield) > 0)
$whatYouWant = array();
{
while($rowpwd = mysqli_fetch_array($getfield))
{
//echo $rowpwd['name'];
$whatYouWant[] = $rowpwd['name'];
}
}
echo '<pre>';
print_r($whatYouWant);
echo '</pre>';
Change:
mysqli_fetch_array
To: If you want key of row
mysqli_fetch_assoc
To:If you want index of row
mysqli_fetch_row
Related
I'm having hard time with this issue
I have multiple queries some data appear in other results...
$query = "SELECT * FROM `hotels`";
$result=mysqli_query($connect,$query);
if(mysqli_num_rows($result)>0) {
while($row=mysqli_fetch_array($result)) {
$hotelname = $row['hotel_name'];
$queryPhotos="SELECT * FROM hotel_photo WHERE hotel_id = ".$row['id']." ";
$resultPhotos=mysqli_query($connect,$queryPhotos);
while($rowPhotos=mysqli_fetch_assoc($resultPhotos)) {
$photos[] = array(
"imgUrl" => $rowPhotos['img_url'],
"hotel_id" => $rowPhotos['hotel_id']
);
}
$apiResult[] = array(
'hotel_name' => $hotelname,
'hotel_photos' => $photos,
);
}
header('Content-type: application/json');
echo json_encode($apiResult, JSON_NUMERIC_CHECK);
}
This is my hotel database
and my hotel_photos database
Why I'm still seeing 'hotel_id 1' in dubai hotel...?
Thank you so much for your help.
You aren't empting the $photos array in every new iteration for a new hotel. Hence, the previous results also exists in the array. You need to fix as below:
<?php
while($row = mysqli_fetch_array($result)) {
$hotelname = $row['hotel_name'];
$photos = []; // add this line
I'm trying to create a dynamic swiper that is able to automatically update itself whenever I make changes in the database. The problem that I've encountered right now is that I've got 6 pictures and description in the swiper but all of them only retrieve from the first field from my database.
Old screenshot of the page. As you can see from the first screenshot I am able to retrieve the data which is the picture and the description from the database, but only repeatingly retrieve from the first field of the database for all the 6 results. Able to show it in the php area. Only the first slider is working when i called the function in html.
Any help would be appreciated, thank you.
<?php
$connect = mysqli_connect("localhost", "root", "", "db");
$result = make_query($connect);
function fetch_array(&$array) {
// Grab the first value from the array
$return = current($array);
// remove the value we just grabbed
array_shift($array);
// if what we have is an array spit it out, else return false
return is_array($return) ? $return : false;
}
function make_query($connect) {
$query = "SELECT * FROM db.slider ORDER BY p_id ASC";
$result = mysqli_query($connect, $query);
return $result;
}
function make_slide_indicators($result) {
$output = '';
$count = 0;
for($i = 0;$i<mysqli_num_rows($result);$i++) {
//for($i = 0;$i<count($result);$i++) {
if ($i == 0) {
$output .= '<li data-target="#" data-slide-to="'.$i.'" class="active"></li>';
} else {
$output .= '<li data-target="#" data-slide-to="'.$i.'"></li>';
}
$count++ === $count = $count + 1;
}
return $output;
}
function make_slides($result) {
$output = '';
$count = 0;
while($row = mysqli_fetch_assoc($result)) {
//while($row = fetch_array($result)) {
// Not needed as the output is the same
if($count == 0) {
$output .= '
<div class="swiper-slide platform">
<img src="'.$row["p_img"].'" alt="'.$row["p_name"].'" />
<div class="swiper-slide platform">
<h3>'.$row["p_desc"].'</h3>
</div>
</div>';
// Not used at the moment
$count++;
}
}
return $output;
}
$connect = mysqli_connect("localhost", "root", "", "db");
$result = make_query($connect);
$result = [['p_img' => 'img','p_name' => 'name','p_desc' => 'desc'],['p_img' => 'img','p_name' => 'name','p_desc' => 'desc'],['p_img' => 'img','p_name' => 'name','p_desc' => 'desc'],['p_img' => 'img','p_name' => 'name','p_desc' => 'desc']];
echo make_slide_indicators($result);
echo PHP_EOL;
echo make_slides($result);
?>
When working with databases use while instead of foreach. The problem you're having is that mysqli_result is not exactly what you think it is, You can have a look here:
https://www.php.net/manual/en/class.mysqli-result.php
Here is a clean version of the code provided. I didn't setup a db for this so to test the logic I implemented a dummy function to work on a set array. I hope the comments are helpful.
function fetch_array(&$array) {
// Grab the first value from the array
$return = current($array);
// remove the value we just grabbed
array_shift($array);
// if what we have is an array spit it out, else return false
return is_array($return) ? $return : false;
}
function make_query($connect) {
$query = "SELECT * FROM db.slider ORDER BY p_id ASC";
$result = mysqli_query($connect, $query);
return $result;
}
function make_slide_indicators($result) {
$output = '';
$count = 0;
//for($i = 0;$i<mysqli_num_rows($result);$i++) {
for($i = 0;$i<count($result);$i++) {
if ($i == 0) {
$output .= '<li data-target="#" data-slide-to="'.$i.'" class="active"></li>';
} else {
$output .= '<li data-target="#" data-slide-to="'.$i.'"></li>';
}
// $count++ === $count = $count + 1;
}
return $output;
}
function make_slides($result) {
$output = '';
// $count = 0;
//while($row = mysqli_fetch_assoc($result)) {
while($row = fetch_array($result)) {
// Not needed as the output is the same
//if($count == 0) { ... } else { ... }
$output .= '
<div class="swiper-slide platform">
<img src="'.$row["p_img"].'" alt="'.$row["p_name"].'" />
<div class="swiper-slide platform">
<h3>'.$row["p_desc"].'</h3>
</div>
</div>';
// Not used at the moment
// $count++;
}
return $output;
}
//$connect = mysqli_connect("localhost", "root", "", "db");
//$result = make_query($connect);
$result = [['p_img' => 'img','p_name' => 'name','p_desc' => 'desc'],['p_img' => 'img','p_name' => 'name','p_desc' => 'desc'],['p_img' => 'img','p_name' => 'name','p_desc' => 'desc'],['p_img' => 'img','p_name' => 'name','p_desc' => 'desc']];
echo make_slide_indicators($result);
echo PHP_EOL;
echo make_slides($result);
The biggest difference in the code is that we're using mysqli_num_rows() in make_slide_indicators(). We don't need to fetch all the data from the mysql result, we just need the number of rows we received.
That solves another problem. If you go trough the whole result with mysqli_fetch_assoc() the next time you would try to work on the same result you would only get the last value. The result has in internal pointer that moves a position forward when a line is read.
If you would ever want to go over a result more then once you'd need to use mysqli_data_seek(). Have a look here:
https://www.php.net/manual/en/mysqli-result.data-seek.php
If you run the code as is You'll see that the logic works correctly. If you still have an issue when you switch to the db connection the problem is there. Here's a quick debug check for you:
$connect = mysqli_connect("localhost", "root", "", "db");
$result = make_query($connect);
echo "Number of rows: ".mysqli_num_rows($result).PHP_EOL;
while($r = mysqli_fetch_assoc($result)) {
var_dump($r);
}
I have a query which I want the results inserted in an array so after all I'll encode it into a JSON, but my problem is that I want the data to be set like this:
array[0] = project1, project2, project3;
array[1] = item1, item2, item3;
and I'm having this:
array[0] = project1;
array[1] = project2;
array[2] = project3;
and so on..
this is what I've done so far:
$info = array();
$items = mysql_query("SELECT * FROM `vision`.`projects` WHERE proj_area = 'area_1'");
if (mysql_num_rows($items) != 0) {
while($proj = mysql_fetch_array($items)) {
$proj_name = $proj['proj_name'];
$proj_beg = $proj['proj_beg'];
$proj_end = $proj['proj_end'];
array_push($info, $proj_name, $proj_beg, $proj_end );
}
}
echo json_encode($info);
my query result gave me these result:
["nome", "0000-00-00", "0000-00-00", "Projeto 2", "2016-12-12", "2020-07-30", "Projeto", "2017-02-03", "2018-03-10"]
and this is my $.getJSON code:
$.getJSON("includes/get_area.php",function(data){
console.log(data);
})
What am I doing wrong?
Try this one; this will add a list in each one of the three array indexes.
$info = array();
$items = mysql_query("SELECT * FROM `vision`.`projects` WHERE proj_area = 'area_1'");
if (mysql_num_rows($items) != 0) {
while($proj = mysql_fetch_array($items)) {
$info[0][] = $proj['proj_name'];
$info[1][] = $proj['proj_beg'];
$info[2][] = $proj['proj_end'];
}
}
echo json_encode($info);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am currently working on a multiple select drop-down list. I need to display the selected values on an edit form.
in_array() is not working as I expect, do I have an error in my logic?
The code to display the selected values from the database is:
<div class="form-group">
<label class="col-md-3 control-label" for="selectbasic">Update Artist Selection</label>
<div class="col-md-6">
<select id="artists1" multiple="multiple" name="id_artist_fk[]" class="form-control ">
<?php
foreach ($artist_list as $key => $value) {
if (in_array($value['id_artist'], $current_artist_list, true)) {
$selected = "selected='selected'";
}
// print_r($value['id_artist']. "==". $current_artist_list);
echo "<option value=\"{$value['id_artist']}\" {$selected}>{$value['name']} {$value['surname']}</option>";
}
?>
</select>
</div>
</div>
The $artist_list is gotten via:
public function get_artist_list() {
$sql = "SELECT * FROM tbl_v_artist WHERE status != 0;";
$result = $this->database->doSelectQuery($sql);
$artists = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_array()) {
$artist = array(
'id_artist' => $row['id_artist'],
'name' => $row['name'],
'surname' => $row['surname'],
'status' => $row['status']
);
array_push($artists, $artist);
}
}
return $artists;
}
The $current_artist_list is gotten via:
$current_artist_list = $vid->get_artistsID_for_video($_POST['id_video']);
get_artistsID_for_video is:
public function get_artistsID_for_video($video_id) {
try {
$sql = "SELECT
tbl_video_artist.id_artist_fk
FROM tbl_video_artist
left join tbl_v_artist
ON tbl_v_artist.id_artist = tbl_video_artist.id_artists
WHERE tbl_video_artist.id_video_fk = {$video_id};";
//echo $sql;
$result = $this->database->doSelectQuery($sql);
$artists = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_array()) {
$artist = array(
'id_artist_fk' => $row['id_artist_fk']
);
array_push($artists, $artist);
}
}
return $artists;
} catch (Exception $ex) {
$ex->getMessage();
$ex->getFile();
}
}
Please help point me in the right direction.
I have edited the get_artistsID_for_video as follows:
public function get_artistsID_for_video($video_id) {
try {
$sql = "SELECT
tbl_video_artist.id_artist_fk
FROM tbl_video_artist
left join tbl_v_artist
ON tbl_v_artist.id_artist = tbl_video_artist.id_artists
WHERE tbl_video_artist.id_video_fk = {$video_id};";
//echo $sql;
$result = $this->database->doSelectQuery($sql);
// $artists = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_array()) {
$artist [] = $row['id_artist_fk'];
// array_push($artists, $artist);
}
return $artist;
}
} catch (Exception $ex) {
$ex->getMessage();
$ex->getFile();
}
}
Look at in_array manual:
in_array — Checks if a value exists in an array
So, what checks your in_array($value['id_artist'], $current_artist_list, true)?
It checks that in $current_artist_list exists value of $value['id_artist']. For example, if $value['id_artist'] is 20, in_array checks if value 20 is in your array.
But value 20 is NOT in your $current_artist_list array.
Because format of each element in your $current_artist_list is array('id_artist_fk' => $row['id_artist_fk']).
So, you're searching for 20, but value which you store is ('id_artist_fk' => 20).
20 NOT EQUALS array.
The fix is in get_artistsID_for_video():
while ($row = $result->fetch_array()) {
$artists[] = $row['id_artist_fk'];
}
Now you search for 20 in array where every element is a number too.
Making your search even faster (still in get_artistsID_for_video):
while ($row = $result->fetch_array()) {
// create array key with value of artist id
$artists[$row['id_artist_fk']] = 1;
}
And replace in_array with:
// check for existence of a key, not value.
if (!empty($current_artist_list[$value['id_artist']])) {
$selected = "selected='selected'";
}
Please check that $current_artist_list must be single array. i.e $current_artist_list[0] = 1;
$current_artist_list[1] = 2;
Which will match your id with condition. Right now it's looks like your $current_artist_list is associative array value having with key. Try to push only value as i mentioned above OR change the code as below.
$artists = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_array()) {
$artist = array(
'id_artist_fk' => $row['id_artist_fk']
);
array_push($artists, $row['id_artist_fk']);
}
}
I just start to use php webservice.I want to take all data in 'urun' table just sending 'id' Here is my code and i dont know how to solve it.
if($_GET["function"] == "getUrun"){
if(isset($_GET["id"]) && $_GET["id"] != ""){
$id = $_GET["id"];
$kategoriid =$_GET["kategoriid"];
$urunadi =$_GET["urunadi"];
$urunfiyati =$_GET["urunfiyati"];
$aciklama =$_GET["aciklama"];
$where="";
$where = "id='".$id."' AND kategoriid='".$kategoriid."' AND urunadi='".$urunadi."' AND urunfiyati='".$urunfiyati."' AND aciklama='".$aciklama."'";
$result = mysql_query("SELECT * FROM urun WHERE ".$where."");
$rows = array();
if($r=mysql_fetch_assoc($result))
{
$rows[] = $result;
$data = json_encode($rows);
echo "{ \"status\":\"OK\", \"getUrun\": ".$data." }";
}else{
echo "{ \"status\":\"ERR: Something wrong hepsi\"}";}
}else{
echo "{ \"status\":\"ERR: Something wrongs hepsi\"}";}
}
It should be:
if ($result) {
$rows = array();
while ($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode(array('status' => 'OK', 'getUrun' => $rows));
} else {
echo json_encode(array('status' => 'ERR: Something wrong hepsi'));
}
You need to get all the results in an array, and then encode the whole thing. You should also use json_encode for the containing object, don't try to create JSON by hand.