How to create a SQL query in PHP with differents variables - php

I have a problem when I create a sql query which depends on many variables that the user select in different checkboxes.
I make a httprequest GET and them, when I proposed to create the query, I check the variable and I create the query, gradually. I show you the PHP code:
$link = mysql_connect($hostname, $username, $password) or die('No se pudo conectar: ' . mysql_error());
//echo 'Conectado satisfactoriamente';
mysql_select_db('Agenda Juvenil') or die('No se pudo seleccionar la base de datos');
mysql_query('SET CHARACTER SET utf8');
$query="SELECT id, title, barrio_smultiple, coordenadas_p_0_coordinate, coordenadas_p_1_coordinate, gratuita_b FROM eventosDiarios WHERE";
// check for post data
if (isset($_GET['franjas0'])){
$franja0 = $_GET['franjas0'];
$query.="franja_smultiple IN ('$franja0'";
}
if (isset($_GET['franjas1'])){
$franja1 = $_GET['franjas1'];
$query.=",'$franja1'";
}
if (isset($_GET['franjas2'])){
$franja2 = $_GET['franjas2'];
$query.=",'$franja2'";
}
$query.=")";
// get a product from products table
$result = mysql_query($query) or die('Consulta fallida: ' . mysql_error());
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["eventos"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$evento = array();
$evento["id"] = $row["id"];
$evento["title"] = $row["title"];
$evento["barrio_smultiple"] = $row["barrio_smultiple"];
$evento["coordenadas_p_0_coordinate"] = $row["coordenadas_p_0_coordinate"];
$evento["coordenadas_p_1_coordinate"] = $row["coordenadas_p_1_coordinate"];
$evento["gratuita_b"] = $row["gratuita_b"];
// push single product into final response array
array_push($response["eventos"], $evento);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No se han encontrado eventos";
// echo no users JSON
echo json_encode($response);
}
The query must return something, but I have nothing. The variables are sent throught
List<NameValuePair> params = new ArrayList<NameValuePair>();
I am using Android.
Can someone help me please??
Thanks in advance.
Regards.

Your code needs to have a space after the WHERE. It needs to say
...b FROM eventosDiarios WHERE ";
rather than
....b FROM eventosDiarios WHERE";
or you'll get an illformed query.

Related

Although I use the same services in 2 different places, I cannot pull data from the database

While I can do anything I want in the database on the free https://volkanguder.000webhostapp.com/envanterler/tum_envanterler.php site, I cannot pull the data on the paid https://volkanguder.info/envanterler/tum_envanterler.php site. When I explained the problem to the relevant place, they stated that there was a problem in the codes I wrote, but the problem was still not solved. Please help.
My Php Service Code;
<?php
// array for JSON response
$response = array();
//DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE değişkenleri alınır.
require_once __DIR__ . '/db_config.php';
// Bağlantı oluşturuluyor.
$baglanti = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
// Bağlanti kontrolü yapılır.
if (!$baglanti) {
die("Hatalı bağlantı : " . mysqli_connect_error());
}
$sqlsorgu = "SELECT * FROM envanterler";
$result = mysqli_query($baglanti, $sqlsorgu);
// result kontrolü yap
if (mysqli_num_rows($result) > 0) {
$response["envanterler"] = array();
while ($row = mysqli_fetch_assoc($result)) {
// temp user array
$envanterler = array();
$envanterler["envanterId"] = $row["envanterId"];
$envanterler["envanterKategori"] = $row["envanterKategori"];
$envanterler["envanterAdi"] = $row["envanterAdi"];
$envanterler["envanterMarka"] = $row["envanterMarka"];
$envanterler["envanterModel"] = $row["envanterModel"];
$envanterler["envanterSerino"] = $row["envanterSerino"];
$envanterler["envanterRfid"] = $row["envanterRfid"];
$envanterler["envanterMahal"] = $row["envanterMahal"];
// push single product into final response array
array_push($response["envanterler"], $envanterler);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No data found";
// echo no users JSON
echo json_encode($response);
}
//bağlantı koparılır.
mysqli_close($baglanti);
?>
MySQL JSON ;
[
{"type":"header","version":"4.9.7","comment":"Export to JSON plugin for PHPMyAdmin"},
{"type":"database","name":"volkangu_envatool"},
{"type":"table","name":"envanterler","database":"volkangu_envatool","data":
[
{"envanterId":"1","envanterKategori":"Bilgisayar ve Çevre Ekipmanları","envanterAdi":"Bilgisayar","envanterMarka":"Dell","envanterModel":"Optiplex 3050 MicroPc","envanterSerino":"12345","envanterRfid":"VG458250","envanterMahal":"MH0102030004"},
{"envanterId":"2","envanterKategori":"Pc ve Donanımlar","envanterAdi":"Monitör","envanterMarka":"Dell","envanterModel":"E2218S","envanterSerino":"12345","envanterRfid":"VG458251","envanterMahal":"MH0102030005"},
{"envanterId":"3","envanterKategori":"Bilgisayar ve Çevre Ekipmanları","envanterAdi":"Klavye","envanterMarka":"Dell","envanterModel":"KB-124-TUR","envanterSerino":"123456789","envanterRfid":"VG458252","envanterMahal":"MH0102030006"}
]
}
]
Free Demo site Service (Working) ;
enter image description here
Hostinger Main site (Not Working) ;
enter image description here
All Hostinger Customer service recommendations

Json return null

I have the next problem doing a json to read in Andorid
(the credentials are hidden but connection going good in others files)
class reportes
{
var $parametro;
var $conexion;
function __construct(){
$host = "IP"; $DBName = "DbName";
$usuario="user"; $contrasena="pass";
$driver = "DRIVER={iSeries Access ODBC Driver};
SYSTEM=$host;Uid=$usuario;
Pwd=$contrasena;Client_CSet=UTF-8;";
$this->conexion = odbc_connect($driver, $usuario, $contrasena);
}
function consulta($parametro){
$query=
"SELECT OHSNME,OHTOT$,OHREPÑ
FROM MYDB.SANFPRD.FOMHDR
WHERE OHORDÑ= $parametro ";
echo $query."<br><br>";
if ($this->conexion == 0) {echo "Ha fallado la conexion a la BBDD </br>";}
else{
$datos = array();
$result=odbc_exec($this->conexion,$query);
while($row = odbc_fetch_object($result)){
$datos[]= $row;
}
echo json_encode($datos);
}
}//Fin funcion consulta()
}//Fin de la clase
$consultar = new reportes();
$nota_venta = $_REQUEST['parametro'];
$consultar->consulta($nota_venta);
the response JSON that i get is:
SELECT OHSNME,OHTOT$,OHREPÑ FROM DELLORTO.SANFPRD.FOMHDR WHERE OHORDÑ= 366
[{"OHSNME":"E.C. GM. ","OHTOT$":"1861.00",null:" A07"}]
you can see that OHORDÑ is probably the problem with the 'Ñ'
but this table are part a productive database and i can't update
Solution #1, alias the column name to a name without non-ascii characters:
$query=
"SELECT OHSNME,OHTOT$,OHREPÑ AS OHREPN
FROM MYDB.SANFPRD.FOMHDR
WHERE OHORDÑ= $parametro ";
Solution #2, manually serialize using utf8_encode():
$result=odbc_exec($this->conexion,$query);
while($row = odbc_fetch_object($result)){
$_row_fix = array();
foreach ($row as $field => $val) {
$_row_fix[utf8_encode($field)] = utf8_encode($val);
}
$datos[]= $_row_fix;
}

Android hindi font not displaying

In my android app.. a result is taken from server and displayed in app.. where two languages are there for user to select.. English and Hindi.. The english part is working fine and displaying correctly. .but for hindi text ,... ony '???????' is displaying insted of fonts... But when I saved hindi fonts in server ..it is displaying as hindi fonts olnly ... I am using php code for connecting with the server..do we need to change it to utf8.. do we need to change any thing in php file.. I am giving my php code and sql code below.. please check and if there any error pls help..
php
<?php
/*
* Following code will get single product details
* A product is identified by product id (pid)
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["pinnum"]))
{
$pinnum = $_GET['pinnum'];
// get a product from products table
$result = mysql_query("SELECT *FROM pin1h WHERE pinnum = $pinnum");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["pid"] = $result["pid"];
$product["pinnum"] = $result["pinnum"];
$product["pinnacle"] = $result["pinnacle"];
$product["created_at"] = $result["created_at"];
$product["updated_at"] = $result["updated_at"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
sql code
CREATE TABLE pin1h(
pid int(11) primary key auto_increment,
pinnum int(11),
pinnacle text,
created_at timestamp default now(),
updated_at timestamp
);
Just a tought but i think you should check the encoding on the server to see if what you send is alright, because i had the same problem one time and it turned out the server was sending the bad string.
<?php
/*
* Following code will get single product details
* A product is identified by product id (pid)
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
mysql_query("SET NAMES 'utf8'");
// check for post data
if (isset($_GET["pinnum"]))
{
$pinnum = $_GET['pinnum'];
// get a product from products table
$result = mysql_query("SELECT *FROM pin1h WHERE pinnum = $pinnum");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["pid"] =$result["pid"];
$product["pinnum"] = $result["pinnum"];
$product["pinnacle"] = $result["pinnacle"];
$product["created_at"] = $result["created_at"];
$product["updated_at"] = $result["updated_at"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>

Unable to get data in proper format

I am unable to parse data in PHP from MySQL.
Here's my code
<?php
header('Content-Type: text/html; charset=utf-8');
// array for JSON response
$response = array();
echo 'भगवान';
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all products from products table
$result = mysql_query("SELECT *FROM create_event") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["create_event"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["id"] = $row["id"];
$product["desc"] = $row["desc"];
$text;
array_push($response["create_event"], $product);
}
// success
$response["success"] = 1;
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
?>
It's my database, I have set all the collation in utf-8 ci format but still not working:
I have tried all possible solutions and help online and have gone through popular posts and answers and also have set browsers settings to support Hindi lang but still displaying ? marks in output. Here is the output format
भगवान{"id":"1","desc":"???? ??????"}
mysql_query('SET character_set_results=utf8');
Use this after connecting to database or before using any select statement.

Checking table in mysql for a name

I'm trying to implement a way to keep names, entered in an android app and sent to a server, from being used again. I figured the easiest way to do this is create another table and every time a product is added the name is added to the name table. I'm very new to php so this may seem like a very simple question but how would I go about checking the table to see if name is already on it.
here is what I go so far(most of it was already there just the commented out is my thought process)
<?php
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['name']) && isset($_POST['longitude']) && isset($_POST['latitude']) && isset($_POST['pavement']) && isset($_POST['traffic']) && isset($_POST['environment'])) {
//if(Name is not already in list of names){
$name = $_POST['name'];
$longitude = $_POST['longitude'];
$latitude = $_POST['latitude'];
$pavement = $_POST['pavement'];
$traffic = $_POST['traffic'];
$environment = $_POST['environment'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO spots(name, longitude, latitude, pavement, traffic, environment) VALUES('$name', '$longitude', '$latitude', '$pavement', '$traffic', '$environment')");
//add new name to table
//$result2 = mysql_query("INSERT INTO names(name) VALUES('$name')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Spot successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
/*
} else {
// name already taken
$response["success"] = 0;
$response["message"] = "Name has already been taken.";
// echoing JSON response
echo json_encode($response);
}
*/
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
Sorry for the simple question but thank you in advance,
Tyler
You could do a SELECT query like this:
$query = mysql_query("SELECT * FROM spots WHERE name='$name'");
$count = mysql_num_rows($query);
if($count == 0){
// name not in database
}
else{
// name is in database
}
However, this is using mysql_ functions which are deprecated. Please use mysqli_ functions instead.
Make name primary key in names table or apply unique constrain and check for duplicate key error after insertion in names table
Or you can first query table to see if name is already there or not
$result3 = mysql_query("SELECT * FROM names WHERE name='$name'");
if(mysql_num_rows($result3) <= 0 )
{
// name is not in names table
// now insert in names table
}

Categories