Json get value from table - php

I have a small code make this result :
{"nomdupharmacie":[{"pid":"71","name":"dft","longi":"9.010505676269531","lati":"34.1575970207261","matricule":"M65203124"},{"pid":"72","name":"erezrzer","longi":"7.529407627880573","lati":"34.63767601827405","matricule":"123"},{"pid":"73","name":"qsd","longi":"8.83832462131977","lati":"35.172592315800905","matricule":"333"}],"success":1}
with this php code :
// get all products from products table
$result = mysql_query("SELECT *FROM nomdupharmacie") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["nomdupharmacie"] = array();
$v = "12";
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["pid"] = $row["pid"];
$product["name"] = $row["name"];
$product["longi"] = $row["longitude"];
$product["lati"] = $row["latitude"];
$product["matricule"] = $row["personnel_number"];
// push single product into final response array
array_push($response["nomdupharmacie"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
i have to test for example :
$value = "555"
if $value exists in column of matricule so get alert
so the questionis how to make test if the value exists in the Matricule column or not ??

You should look into using PDO or ADOdb instead of mysql_query which is deprecated.
The only option is to compare manually like this:
1) create a function that receives an array x and value v to check
function isMatriculeInArray($x, $v)
{
foreach($x as $z)
{
if($z["matricule"] == $v)
{
return true;
}
}
return false;
}
2) check if matricule is in there
if(!isMatriculeInArray($response["nomdupharmacie"], $v)
{
array_push($response["nomdupharmacie"], $product);
}

Related

How to insert array values in mysql with a loop

Reading a Textarea with jquery , splitting each line in Array then with ajax posting that array in mysql through php but in results only first value inserted.
Table:
CREATE TABLE IF NOT EXISTS addresses (
id int(8) NOT NULL PRIMARY KEY,
user_id int(8) DEFAULT NULL,
address_value varchar(100) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Here is Jquery Code :
$('#insertad').click(function(){
var lines = $('#txtArea').val().split('\n');
var phparray = new Object();
for(var i = 0;i < lines.length;i++){
phparray[i] = lines[i]; //store value in object
}
$.post('functions.php?action=insertad', {array1:$.param(phparray)}, function(resp){
$('.text-success').html(resp);
if(resp == 'Added'){
$('.text-success').html('Added Address :');
}
});
});
Here is PHP Code :
if ($action == 'insertad') {
$pieces = explode('&', $_POST['array1']); //explode passed serialized object
$phparray = array();
foreach ($pieces as $piece) {
list($key, $value) = explode('=', $piece);
$phparray[$key] = $value; //make php array
}
$length = count($phparray);
for ($i = 0; $i < 7; $i++) {
$sql = "select address_value from addresses where address_value = '$phparray[$i]'";
$qry = mysql_query($sql);
$numrows = mysql_num_rows($qry);
if ($numrows > 0) {
echo "One Found !!" ;
} else {
$sql = "insert into addresses (address_value) values ('$phparray[$i]')";
$qry = mysql_query($sql);
if ($qry) {
echo "Added";
}
}
}
}
Try this please...
JS:
var $textarea = $('textarea'); // maybe you have to specific your selector!
var textArray = $textarea.val().split("\n"); // this array is already done, your have not todo next for() loop
$.post('functions.php', {
action: 'insertad',
array1: textArray
}, function(results) {
$.each(results, function(reslt) {
if(result === 'Added') {
$('.status').append(result);
}
else {
$('.status').append(result);
}
});
});
PHP:
if($action === 'insertad') {
$results = [];
$input = $_POST['array1'];
foreach($input AS $textLine) {
$escapedTextLine = mysqli_real_escape_string($resource, $textLine);
$result = mysqli_query($resource, 'select address_value from addresses where address_value = "'.$escapedTextLine.'"');
$affectedRows = mysqli_num_rows($result);
if($affectedRows > 0) {
$results[] = 'One Found !!';
}
else {
$result = mysqli_query($resource, 'INSERT INTO `adresses` (`address_value`) VALUES("'.$escapedTextLine .'");
if($result) {
results[] = 'Added!';
}
}
}
return $results; // we return all done results to check this array in ajax response
}
Notice: I wrote the code blind, so maybe you have to make some small changes for e.g. your variables or something like that.
Notice 2: I write the code with mysqli, so you have to rewrite your Database connection setup code.
Please never forget to use mysqli_real_escape_string do something with user contents.

Why doesn't my shopping cart count products of the same type?

This is the code so far.
I know its not very secure for injections, I'll take care of that later.
but my problem is that my cart adds product but sometimes i get the:
Unsupported operand types in E:\HostingSpaces\Knoppers1\topjop.nl\wwwroot\portal\core\tj_functions.php on line 358
error and i can't add multiple items of the same type.
line 358: $_SESSION['cart'][$uid] += 1;//
Maybe some of you know because other related questions didn't helped me.
function toevoegen(){
session_start();
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = array();
}
if(isset($_GET['add'])) {
$info = 'U heeft een product toegevoegd <META HTTP-EQUIV=REFRESH CONTENT="1; URL=http://topjop.nl/portal/winkelmandje.php">';
$uid = 0; //update id
foreach($_SESSION['cart'] as $id => $data){
if($data[0]==$_GET['add']){
$uid = $id;//
}
}
if($uid == 0){
array_push($_SESSION['cart'],array($_GET['add'],1));//
}else{
$_SESSION['cart'][$uid] += 1;//
}
}
else {
$info = '';
}
return $info;
}
function winkelmandje(){
mysql_connect("mysql8.mijnhostingpartner.nl","","");
mysql_select_db("Knoppers1_portal");
session_start();
$mand = '<table id="winkelmandje_tabel"><tr><td>Product</td>
<td>Stukprijs</td><td>Aantal</td><td>Totaal bedrag</td><td></td></tr>';
foreach($_SESSION['cart'] as $data){
$id = $data[0];//
$value = $data[1];//
if($value>0){
$get = mysql_query('SELECT id, name, price FROM products WHERE id='.mysql_real_escape_string((int)$id));
while ($get_row = mysql_fetch_assoc($get)) {
$totaal = $get_row['price']*$value;
$totaalprijs = number_format($totaal,2,',','.');
$mand .= '<tr><td>'.$get_row['name'].'</td>
<td>€'.$get_row['price'].'</td><td>'. $value .'</td> <td>€'.$totaalprijs.'</td></tr>';
}
}
else{
}
}
$aantal = '';
$kosten = '';
return $mand.'<tr><td><b>Totaal:</b></td><td></td><td><b>'. $aantal .'</b></td><td><b>'. $kosten .'</b></td></tr></table>';
}
toevoegen = ADD<br>
winkelmandje = SHOPPINGCART
Seems like $_SESSION['cart'][$uid] is an array containing id and value as you read it like that in the follwoing snippet:
$id = $data[0];//
$value = $data[1];//
it seems $_SESSION['cart'][$uid] is an array. so you can't do +=1
maybe do
$_SESSION['cart'][$uid][1] += 1; // increment $value

PHP Arrays between 2 Functions

i used an exsiting code from a tutorial and need to change it.
The original code doesnt use an array, but i need it.
In my index.php i am calling the function with a tag:
else if ($tag == 'getinvbykost') {
$kstalt = $_POST['kstalt'];
$get = $db->GetInvByKost($kstalt);
if ($get != false) {
// echo json with success = 1
$response["success"] = 1;
$response["ean"] = $get["ean"];
$response["name"] = $get["name"];
$response["betriebsdatenalt"] = $get["betriebsdatenalt"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "nicht erfolgreich";
echo json_encode($response);
}
}
the function GetInvByKost($kstalt); is defined in DB_Functions.php.
the part is:
public function GetInvByKost($kstalt) {
$result = mysql_query("SELECT ean, name, betriebsdatenalt FROM geraete WHERE kstalt='$kstalt' AND accepted='0'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
while ($result = mysql_fetch_assoc($result)){
}
return $result;
//echo $result[1];
}
else {
// user not found;
return false;
}
}
the problem is, the function GetInvByKost returns an array.
the part in the index.php
$response["success"] = 1;
$response["ean"] = $get["ean"];
$response["name"] = $get["name"];
$response["betriebsdatenalt"] = $get["betriebsdatenalt"];
isnt made for an array, only for a single line.
how do i can get the values in the array to build my output?
mysql_fetch_assoc($result) returns a flat array. This means you can't access returned array by a key. So $get["ean"] is wrong and $get[1] is correct. You can access result of mysql_fetch_assoc($result) only by index, not key. You have SELECT ean, name, betriebsdatenalt... in your query, so index of "ean" is equal to 0, "name" is equal to 1 and so on. Therefore, 3 parts of your code should be change in this way:
`$get["ean"]` => ` $get[0]`
`$get["name"]` => `$get[1]`
`$get["betriebsdatenalt"]` => `$get[2]`
Update:
So, the index.php file should be like this:
else if ($tag == 'getinvbykost') {
$response = array();
$kstalt = $_POST['kstalt'];
$get = $db->GetInvByKost($kstalt);
if ($get != false) {
// echo json with success = 1
$response["success"] = 1;
$response["ean"] = $get[0];
$response["name"] = $get[1];
$response["betriebsdatenalt"] = $get[2];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "nicht erfolgreich";
echo json_encode($response);
}
}

Foreach loop full execution and stop the rest of the script

I have a product table from where I am checking that quantity for respective product id(s) is valid or not..
this is the code snippet :
$pids = explode(',',$pid); /*in the form of 2,3,4.....*/ /*$pid->product_id*/
$q = explode(',',$q_total); /*in the form of 2,3,4.....*/ /*$q->quantity*/
/*checking start*/
foreach($pids as $index => $ps){
$quants = $q[$index];
$sql = $stsp->query("SELECT quantity FROM product WHERE id='$ps'");
$row = $sql->fetch(PDO::FETCH_ASSOC);
$quantity_rem = $row['quantity'];
if($quants > $quantity_rem){
$array = array();
$array['errquant'] = 'wrong_quant';
$array['error_pr'] = $ps;
echo json_encode($array);
exit; /*stop the rest of the code from executing*/
}
}
/*rest of the code outside the loop*/
So here what is happening is it checks the quantity ($quantity_rem) from table of a product id and if that quantity is less than the quantity given ($q), then the script stops and echo the product id..
But I have more that 1 product .. It's not checking the rest since whenever there is a fault it stops and echo out. I want to check all the products and echo out the product id(s) and stop the rest of the script outside the loop..
Help needed!
Thanks.
and please don't talk to me about sql injection because i know it is vulnerable and i will take care of that..
Try this:
$pids = explode(',',$pid); /*in the form of 2,3,4.....*/ /*$pid->product_id*/
$q = explode(',',$q_total); /*in the form of 2,3,4.....*/ /*$q->quantity*/
/*checking start*/
$errors = array();
foreach($pids as $index => $ps){
$quants = $q[$index];
$sql = $stsp->query("SELECT quantity FROM product WHERE id='$ps'");
$row = $sql->fetch(PDO::FETCH_ASSOC);
$quantity_rem = $row['quantity'];
if($quants > $quantity_rem){
$array = array();
$array['errquant'] = 'wrong_quant';
$array['error_pr'] = $ps;
$errors[] = $array;
}
}
echo json_encode($errors);
foreach($pids as $index => $ps){
$quants = $q[$index];
$sql = $stsp->query("SELECT quantity FROM product WHERE id='$ps'");
$row = $sql->fetch(PDO::FETCH_ASSOC);
$quantity_rem = $row['quantity'];
$array = array();
if($quants > $quantity_rem){
$array[$ps]['errquant'] = 'wrong_quant';
// note little change - you will get array with product ids as key
//and qty error assigned to them
}
echo json_encode($array);
exit; /*stop the rest of the code from executing*/

Php: loop breaks when call a method inside a while in a class

I have a problem in a class I can't solve, the loop breaks in getAlojamiento() when I call getImagenes() inside the while. In this case getAlojamiento() returns only one row, it should return all the rows. Here are the methods involved:
//THIS GETS THE ROWS FROM A TABLE AND RETURN AN ARRAY, IF $id IS SET, CHECKS IF id_asoc == $id
public function getImagenes($table, $id=false){
$return = '';
//checks if id id == true
if($id){
$sql="SELECT * FROM $table WHERE id_asoc = '$id' ORDER BY id DESC";
}else{
$id = '';
$sql="SELECT * FROM $table ORDER BY id DESC";
}
//this make the sql request (returns an array)
if(!$this->MySQLQuery($sql)){
$return = false;
}else{
if($this->dbNumberRows == 0){ //cheks if there are results
$return = false;
}else{ //if has results makes and fills an array
$items = array();
while($f = mysql_fetch_object($this->dbResults)){
$items[$f->id]['id'] = $f->id;
$items[$f->id]['id_asoc'] = $f->id_asoc;
$items[$f->id]['comentario'] = htmlentities($f->comentario);
$items[$f->id]['nombre'] = htmlentities($f->nombre);
}
$return = $items;
}
}
return $return;
}
//THIS GETS THE ROWS FROM A TABLE AND RETURN AN ARRAY
public function getAlojamiento($id=false){
$return = '';
//checks if id id == true
if($id){
$sql="SELECT * FROM tb_alojamiento WHERE id = '$id' LIMIT 1";
}else{
$id = '';
$sql="SELECT * FROM tb_alojamiento ORDER BY titulo ASC";
}
//this make the sql request (returns an array)
if(!$this->MySQLQuery($sql)){
$return = false;
}else{
if($this->dbNumberRows == 0){ //cheks if there are results
$return = false;
}else{ //if has results makes and fills an array
$items = array();
while($f = mysql_fetch_object($this->dbResults)){
$imagenes_arr = $this->getImagenes('tb_alo_imagenes', $f->id); //this is causing the break
$items[$f->id]['id'] = $f->id;
$items[$f->id]['titulo'] = $f->titulo;
$items[$f->id]['telefono'] = $f->telefono;
$items[$f->id]['descripcion'] = $f->descripcion;
$items[$f->id]['email'] = $f->email;
$items[$f->id]['url'] = $f->url;
$items[$f->id]['direccion'] = $f->direccion;
$items[$f->id]['ubicacion'] = $f->ubicacion;
$items[$f->id]['coordenadas'] = $f->coordenadas;
$items[$f->id]['disponibilidad'] = $f->disponibilidad;
$items[$f->id]['tarifas'] = $f->tarifas;
$items[$f->id]['servicios'] = $f->servicios;
$items[$f->id]['theme'] = $f->theme;
$items[$f->id]['premium'] = $f->premium;
$items[$f->id]['img_ppal_id'] = $f->img_ppal_id;
$items[$f->id]['imagenes'] = $imagenes_arr;
}
$return = $items;
}
}
return $return;
}
The problem is that you are using $this->dbResults for both queries. When you call getImagenes you are clobbering the dbResults in getAlojamiento.
A simple solution to avoid having the first mysql query affect other queries is to complete it first:
//first loop over the result set from first query
while($f = mysql_fetch_object($this->dbResults))
{
//note: no call to $this->getImagenes here!
$items[$f->id]['id'] = $f->id;
$items[$f->id]['titulo'] = $f->titulo;
....
}
//only now you fetch the images in a second pass
foreach( $items as $id => $item )
{
$items[$id]['imagenes'] = $this->getImagenes('tb_alo_imagenes', $id);
}
//return the complete $items array
$return = $items;
while($f = mysql_fetch_object($this->dbResults)){
$items[$f->id]['id'] = $f->id;
$items[$f->id]['id_asoc'] = $f->id_asoc;
$items[$f->id]['comentario'] = htmlentities($f->comentario);
$items[$f->id]['nombre'] = htmlentities($f->nombre);
}
$return[] = $items;
You're setting the array to be the single $items array. You need to add it to the $return array.

Categories