PHP repeated results - php

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

Related

Problem in duplication after clicking submit button multiple times

My main problem is with that code in which when I click on submit buttons many times, it inserts duplication many times in the database in which I need to avoid that. Please help me to solve this problem. These are the two tables in which I am trying to insert. mat_ans_options_choose and mat_answer.
$val = $this->input->post(null, true);
$val['id'] = $this->input->post('id');
$val['sub_type'] = $this->input->post('sub_type');
$val['timeout'] = $this->input->post('timeout');
$val['level'] = $this->input->post('level');
$val['mat_category'] = $this->input->post('mat_category');
$option = $val['option'] = $this->input->post('option');
$type = $this->input->post('type');
$marks = [];
$uid = $this->session->userdata('id');
if (isset($val['id']) && isset($option)) {
$query = $this->db->query("SELECT * FROM mat_ans_options WHERE deleted=0 AND active=1 AND question=" . $val['id']);
$result = $query->result_array();
if ($query->num_rows() > 0) {
$count1 = 1;
foreach ($result as $res) {
if ($res['marks'] == 1) {
break;
} else {
$count1++;
}
}
}
// MAT answers options choose
$query1 = $this->db->query("SELECT * FROM mat_ans_options_choose WHERE deleted=0 AND active=1 AND uid=$uid AND q=" . $val['id']);
$result1 = $query1->result_array();
if ($query1->num_rows() > 0) {} else {
$data1 = [
'uid' => $uid,
'q' => $val['id'],
'option_chose' => $option,
'createdon' => $this->general_model->server_time(),
];
$this->db->insert('mat_ans_options_choose', $data1);
}
if ($count1 == $option) {
$marks = 1;
} else {
$marks = 0;
}
// if($marks==1 || $marks==0)
// {
// MAT answers
$query2 = $this->db->query("SELECT * FROM mat_answers WHERE deleted=0 AND active=1 AND uid=$uid AND q=" . $val['id'] . " AND type=" . $type . " AND sub_type=" . $val['sub_type'] . " AND level=" . $val['level']);
$result2 = $query2->result_array();
if ($query2->num_rows() > 0) {} else {
$data = [
'uid' => $uid,
'q' => $val['id'],
'type' => $type,
'level' => $val['level'],
'sub_type' => $val['sub_type'],
'mat_category' => $val['mat_category'],
'marks' => $marks,
'timeoutstatus' => $val['timeout'],
'createdon' => $this->general_model->server_time(),
];
$this->db->insert('mat_answers', $data);
}
// }
return 1;
} else {
return 0;
}
Use JS in which you disable the button after first click - it will work no matter if you are using AJAX or not.
You can use JS/jQuery to limit the number of requests made on the client side. For example by disabling the button on submit:
$("#my-button").prop("disabled", true);
But if the data is sensitive for duplicates (orders, user registration etc) you should make the request limit server side with PHP. You can achieve this by adding a unique index to the tables, either on user id or on a unique token that is submitted with the html form.
Create UNIQUE index in database for uid and q. The database will not insert same question's id from same user's id mulitple times.

Auto increment Invoice ID in Code-igniter

i am very new to code igniter /php .
Before i was using randomly generated invoice number like
$invoice_no = rand(9999,9999999999);
But now i wanted to increment invoice number and add current year as a prefix to it . But somewhere i am doing wrong as this code failed execute . Can some one point me in the right direction .
My model is ...
function insertInvoice($data)
{
$this->db->trans_begin();
$invoice = array();
if(!empty($data['client_id']))
{
$invoice['invoice_client_id'] = $data['client_id'];
}else{
$client_data = array(
'client_name' => $data['customername'],
'client_address1' => $data['address1']
);
$this->db->insert('client_details', $client_data);
$insert_id = $this->db->insert_id();
$invoice['invoice_client_id'] = $insert_id;
}
$query = $this->db->query("SELECT * FROM invoice ORDER BY invoice_id DESC LIMIT 1");
$result = $query->result_array(0);
$result ++;
$curYear = date('Y');
$invoice_no = $curYear . '-' .$result;
$invoice['invoice_no'] = $invoice_no;
$invoice['invoice_subtotal'] = $data['subTotal'];
$invoice['invoice_tax'] = $data['tax'];
$invoice['invoice_tax_amount'] = $data['taxAmount'];
$invoice['invoice_total'] = $data['totalAftertax'];
$invoice['invoice_total_extra'] = $data['totalextra'];
$invoice['invoice_rent'] = $data['rent'];
$invoice['invoice_paid'] = $data['amountPaid'];
$invoice['invoice_due'] = $data['amountDue'];
$invoice['invoice_desc'] = $data['notes'];
$invoice['invoice_items_count'] = $data['item_count'];
$invoice['invoice_extra_count'] = $data['extra_count'];
$invoice['invoice_miscellaneous'] = $data['miscellaneous'];
$this->db->insert('invoice', $invoice);
$i=1;
do {
$items = array(
'invoice_no' => $invoice_no,
'item_name' => $data['invoice']['product_name'][$i],
'item_price' => $data['invoice']['product_price'][$i],
'item_qty' => $data['invoice']['product_qty'][$i],
'item_total' => $data['invoice']['total'][$i],
'item_noof_crate_wait' => $data['invoice']['noof_crate_wait'][$i],
'item_crate_wait' => $data['invoice']['crate_wait'][$i],
'item_choot' => $data['invoice']['choot'][$i],
'item_net_quantity' => $data['invoice']['net_qty'][$i]
);
$this->db->insert('invoice_items',$items);
$i++;
} while($i<$data['item_count']);
$j=1;
do {
$extraitems = array(
'invoice_no' => $invoice_no,
'extra_item_name' => $data['extra']['name'][$j],
'extra_item_qunatity' => $data['extra']['qty'][$j],
'extra_item_price' => $data['extra']['price'][$j],
'extra_item_total' => $data['extra']['total'][$j]
);
$this->db->insert('extra_items',$extraitems);
$j++;
} while($j<$data['extra_count']);
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
return FALSE;
}
else
{
$this->db->trans_commit();
return TRUE;
}
}
invoice_id is primary key in DB .
You're attempting to increment the result array but what you really need is to acquire and increment a field value.
//you only need one field so ask only for that
$query = $this->db->query("SELECT invoice_id FROM invoice ORDER BY invoice_id DESC LIMIT 1");
//you really should check to make sure $query is set
// before trying to get a value from it.
//You can add that yourself
//Asked for only one row, so only retrieve one row -> and its contents
$result = $query->row()->invoice_id;
$result ++;
...
I'm guessing you're getting an "Object conversion to String error" on line $invoice_no = $curYear . '-' .$result;
Since $result contains an object and you're using it as a string. Print the $result variable to check how to use the data assigned to it.

Php in_array() not working as expected [closed]

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']);
}
}

json_encode adding a null:null entry

I have this code - it's not done by me :s and don't have time to replace the deprecated calls.
<?php
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
umask(0);
Mage::app();
$db=mysql_connect('localhost','carros_mil1','K-Jw)ureB.}M');
mysql_select_db('carros_mil0',$db);
$nombreListModelo = 'modelo_'.str_replace(" ","_",strtolower($_REQUEST['nombreMarca']));
$sql = "SELECT DISTINCT (identificador) AS id
FROM modelos
WHERE nombre = '".$nombreListModelo."'";
$rs=mysql_query($sql);
$i=0;
while ($row = mysql_fetch_array($rs)) {
$vectorModelo[$i] = $row['id'];
$i++;
}
$sql = "SELECT attribute_id
FROM eav_attribute
WHERE attribute_code = '".$nombreListModelo."'";
$rs = mysql_query($sql);
$row = mysql_fetch_array($rs);
$id1 = $row['attribute_id'];
$sql= "SELECT eao.option_id AS option_id
FROM eav_attribute_option eao, eav_attribute_option_value eaov
WHERE eao.option_id=eaov.option_id AND attribute_id = ".$id1." ORDER BY eaov.value";
$rs=mysql_query($sql);
$retorno = array();
$bandera = true;
while ($row = mysql_fetch_array($rs)) {
$bandera = false;
$sql2= "SELECT value, option_id
FROM eav_attribute_option_value
WHERE option_id = ".$row['option_id']."
ORDER BY value";
$rs2=mysql_query($sql2);
$row2= mysql_fetch_array($rs2);
if ($_REQUEST['bandera']=='vende') {
if (!is_null($row2['value'])) $retorno[$row2['value']] = $row2['value'];
} else {
$existe=false;
for($k=0;$k<count($vectorModelo);$k++) {
if($row2['option_id'] == $vectorModelo[$k]) {
$existe=true;
break;
}
}
if($existe) {
if($_REQUEST['tipo']=='contactenos')
if (!is_null($row2['value'])) $retorno[$row2['value']] = $row2['value'];
else
if (!is_null($row2['option_id'])) $retorno[$row2['option_id']] = $row2['value'];
}
}
}
if($bandera)
$retorno[''] = 'Todos';
header('Content-Type: application/json');
//echo json_encode($retorno);
foreach($retorno as $k => $v) {
printf("%s => %s\n", $k, $v);
}
print_r($retorno);
echo json_encode($retorno);
Since I noticed something strange in the generated json, I added 2 different ways of printing the contents of the array.
The JSON way adds me a null:null entry. The strange case is that I'm checking !is_null($row2['value']) each time I add an element.
When I hit the url under certain parameters, I get:
Elantra => Elantra
Getz => Getz
H1 => H1
i-10 => i-10
New Accent => New Accent
Santa Fé => Santa Fé
Tucson => Tucson
Array
(
[Elantra] => Elantra
[Getz] => Getz
[H1] => H1
[i-10] => i-10
[New Accent] => New Accent
[Santa Fé] => Santa Fé
[Tucson] => Tucson
)
{"Elantra":"Elantra","Getz":"Getz","H1":"H1","i-10":"i-10","New Accent":"New Accent",null:null,"Tucson":"Tucson"}
The first 6 lines correspond to a custom print foreach loop. There's also a print_r call which only shows 6 elements. The 3rd form - which is the actual one I need - shows a null value.
So: Why is $retorno accepting null entries when I check the null condition beforehand? considering this script is full - no missing code here.
(Thanks #Hammerstein - don't know why you didn't write that as an answer).
The problem is that one of such values was not correctly being encoded, since it was not an ANSI value and was not encoded in UTF8. In this way, since "Santa Fé" had a "strange" character, it was encoded as null instead of "Santa F\u00e9".
Tip: Never assume your database is using an utf8_ charset
The solution was to explicitly encode the values when composing the array:
...
$bandera = false;
$sql2= "SELECT value, option_id
FROM eav_attribute_option_value
WHERE option_id = ".$row['option_id']."
ORDER BY value";
$rs2=mysql_query($sql2);
$row2= mysql_fetch_array($rs2);
//ENCODE the values to a good charset
$value = utf8_encode($row2['value']);
$option_id = utf8_encode($row['option_id'])
if ($_REQUEST['bandera']=='vende') {
$retorno[$value] = $value;
} else {
$existe=false;
for($k=0;$k<count($vectorModelo);$k++) {
if($row2['option_id'] == $vectorModelo[$k]) {
$existe=true;
break;
}
}
if($existe) {
if($_REQUEST['tipo']=='contactenos')
$retorno[$value] = $value;
else
$retorno[$option_id] = $value;
}
}
...

how to take data in mysql database with using php web service

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.

Categories