I'm making an intranet.
Only admin have access to the page i want to build now :
I have a page with a textarea. When they click on the send button, it comming to a PHP page to send a req like "UPDATE ... " or "SELECT ...".
He can write the SQL request he want. It's supposed to works.
I want it to work : If it's an update i need to return he if it's ok, if its a select i need to return a table.
But i need it to be able to exec complex request like :
SELECT numfou,
(SELECT COUNT(*)
FROM PROPOSER P
WHERE P.numfou = F.numfou) AS NB_PROD
FROM FOURNISSEUR F;
(net exemple).<br/>
Do you know a PHP code to exec any SQL req?
I suggest this code i make (If you think it can be update say it :D) :
<?php
function requette($req){
$premierMot = explode(" ", $req)[0];
switch(strtoupper($premierMot)){
case "SELECT":
return select($req);
break;
case "UPDATE":
case "DELETE":
case "INSERT":
return updateDeleteInsert($req);
break;
}
}
function select($req){
$bdd = new PDO('mysql:host=localhost;dbname=spb', 'root', '');
// ON DETERMINE SI LE CLIENT RECHERCHE DANS CHAMPS EN PARTICULIER OU TOUT
$explosion = preg_split('/[;, \n]+/', $req);
$veuxTout = false;
for($cpt=0;$cpt<count($explosion);$cpt++){
if(strtoupper($explosion[$cpt]) == "*"){
$veuxTout = true;
break;
}
}
// SI IL NE VEUX PAS TOUT ON PREVOI UN TABLEAU DE DEMANDE
$demande = array();
for($cpt=1;$cpt<count($explosion);$cpt++){
if(strtoupper($explosion[$cpt]) == "FROM"){
break;
}
else{
array_push($demande,$explosion[$cpt]);
}
}
// ON CHERCHE LE NOM DE LA TABLE
$table = "";
for($cpt=0;$cpt<count($explosion);$cpt++){
if(strtoupper($explosion[$cpt]) == "FROM"){
$table = $explosion[$cpt+1];
break;
}
}
// ON CHERCHE LES TITRES DE LA TABLE
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='$table';";
$res = $bdd->query($sql);
$titres = array();
while($resultat = $res->fetch()){
array_push($titres,$resultat['COLUMN_NAME']);
}
$res = $bdd->query($req);
$table = "<table>";
while($resultat = $res->fetch()){
$table .= "<tr>";
if($veuxTout == true){
for($cpt=0;$cpt<count($titres);$cpt++){
$table .= "<td>".$resultat[$titres[$cpt]]."</td>";
}
}
else{
$ok = false;
for($cpt1=0;$cpt1<count($titres);$cpt1++){
for($cpt2=0;$cpt2<count($demande);$cpt2++){
if(strtoupper($titres[$cpt1]) == strtoupper($demande[$cpt2])){
$table .= "<td>".$resultat[$titres[$cpt1]]."</td>";
$ok = true;
}
}
}
}
$table .= "</tr>";
}
$table .= "</table>";
return $table;
}
function updateDeleteInsert($req){
$bdd = new PDO('mysql:host=localhost;dbname=spb', 'root', '');
try {
$req = $bdd->prepare($req);
$req->execute();
return "oui";
}
catch(PDOException $e){
return "non";
}
}
$req = htmlentities($_POST['req']);
echo requette($req);
?>
Related
I have an input in my code that update a value in MySQL, but is not working, if i set the value manually in PHPMyAdmin, the value display in HTML, but when i try update, return to 0.
I have the same code to do a similar function, and have copied, and it still isn't working.
Controller:
function ordemmobile(){
$ordemmobile = $this->input->post('ordemmobile');
$id = $this->input->post('id');
if($id > 0){
$data['ordemmobile'] = $ordemmobile;
$data['id'] = $id;
if( $this->categorias_model->alterar($data)){
$ret = "success";
$msg = "Ordem alterada com sucesso!";
}else{
$ret = "danger";
$msg = "Erro ao alterar a ordem :(";
}
}else{
$ret = "danger";
$msg = "Erro ao alterar a ordem :(";
}
echo json_encode(array('status' => $ret , 'msg' => $msg));
}
View:
echo "<td><input type=\"number\" name=\"ordemmobile\" value=\"".$registro->ordemmobile."\" style=\"width:80px; margin:0\" class=\"ordemmobile\" data-id=\"".$registro->id."\" data-url=\"".base_url('adm/'.$this->router->fetch_class().'/ordemmobile')."\" /><span style=\"display:none\">".$registro->ordemmobile."</span></td>";
Model (alterar):
function alterar($data){
$this->db->where('id',$data['id']);
return $this->db->update('ga845_categorias',$data);
}
Looks like it should work if the inputs are getting posted. Checking both inputs would be a good idea.
Consider this
function ordemmobile()
{
$ordemmobile = $this->input->post('ordemmobile');
$id = $this->input->post('id');
if(empty($id) || empty($ordemmobile))
{
$ret = "danger";
$msg = "Erro ao alterar a ordem :(";
}
else
{
$data['ordemmobile'] = $ordemmobile;
$data['id'] = $id;
if($this->categorias_model->alterar($data))
{
$ret = "success";
$msg = "Ordem alterada com sucesso!";
}
else
{
$ret = "danger";
$msg = "Erro ao alterar a ordem :(";
}
}
echo json_encode(array('status' => $ret, 'msg' => $msg));
}
You should also take a good look at what your browser's Web Developer Tools tell you about the request to and response from the server.
I'm trying to do a simple select and send it via SMS Gateway but when I send the message that should run the function nothing happens. This is the function that i wrote. Sender should send "utakmice x" where the x is the number of the next x events that are sent from the database:
function utakmice($broj) {
$conn = connect();
if ($conn->connect_error) {
$smsporuka = "Ne moze se uspostaviti konekcija sa bazom, pokusajte kasnije.";
} else {
$query = "SELECT * FROM utakmica ORDER BY datum LIMIT = $broj;";
$rezultat = mysql_query($query);
if($rezultat) {
if(mysql_num_rows($rezultat) !== 0) {
$smsporuka="";
while($red = mysql_fetch_array($rezultat)) {
$smsporuka .= "(".$red["id_tekma"]." ".$red["protivnik"].",".$red["cena"]."RSD datum: ".$red["datum"].")";
}
} else {
$smsporuka = "Nema selektovanih utakmica!";
}
}
}
disconnect($conn);
sendResponse($smsporuka);
}
Here is the code before the functions, function info works as it's supposed to work:
function sendResponse($t) {
$reply = rawurlencode($t);
header("Content-Type: text/html; charset=utf-8");
header("text: ".$reply);
}
if(empty($text) || strlen($text) == 0 || $text == "") {
$smsporuka = "Poslali ste sms poruku u losem formatu, za vise informacija posaljite INFO.";
sendResponse($smsporuka);
} else {
$text = str_replace(";", "", $text);
$explodeovanText = explode(' ',trim($text));
$komanda = strtolower($explodeovanText[0]);
switch ($komanda) {
case "info":
info();
break;
case "utakmice":
utakmice($explodeovanText[1]);
break;
case "dodaj":
dodaj($explodeovanText[1], $explodeovanText[2]);
break;
case "rezervisi":
rezervisi($explodeovanText[1], $explodeovanText[2]);
break;
case "otkazi":
otkazi($explodeovanText[2]);
break;
}
}
function info() {
$smsporuka = "Posaljite UTAKMICA da bi ste videli narednih 5 protivnika i datume utakmica. Posaljite REZ_x_y, gde je x id utakmice, a y broj mesta koje rezervisete.";
sendResponse($smsporuka);
}
I solved it! mysql functions were supposed to be mysqli and the query was not correct. Here is the solution. Also in the beginning I set the default parameter to be 5.
function utakmice($broj = 5) {
$smsporuka = "";
$conn = connect();
if ($conn->connect_error) {
$smsporuka = "Ne moze se uspostaviti konekcija sa bazom, pokusajte kasnije.";
} else {
$query = "SELECT * FROM utakmica ORDER BY datum LIMIT $broj;";
$rezultat = mysqli_query($conn, $query);
if($rezultat) {
if(mysqli_num_rows($rezultat) !== 0) {
$smsporuka="";
while($red = mysqli_fetch_array($rezultat)) {
$smsporuka .= "(".$red["id_tekma"]." ".$red["protivnik"].",".$red["cena"]."RSD datum: ".$red["datum"].")";
}
}
else {
$smsporuka = "Nema selektovanih utakmica!";
}
}
}
disconnect($conn);
sendResponse($smsporuka);
}
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;
}
I want to browse data from my postgre database with a "foreach". So I made my request like that :
$conn_string = "host=localhost port=5432 dbname=test_postgre user=postgres password='1234'";
$dbconn = pg_connect($conn_string);
$sql = "SELECT id_traitement FROM public.traitement WHERE id_essai='.$id_essai.';";
$res = pg_query($sql) or die("Pb avec la requete: $sql");
$data = pg_fetch_all($res);
And I get my values with "pg_fetch_all".
After that, I'm looking for compare the data in my database (get with the request) and the data in my web page. So I created this loop :
foreach($array as $ligne_web)
{
foreach($data['id_traitement'] as $ligne_base)
{
if(($ligne_web[0] == $ligne_base) and ($flag))
{
//update de la ligne
update_traitement($id_traitement,$traitement,$code_traitement,$id_essai);
$flag2 = false;
break 1;
}
}
if(($flag) and ($flag2))
{
insert_traitement($id_traitement,$traitement,$code_traitement,$id_essai);
}
}
When I try to run it, firebug tells me : Invalid argument supplied for foreach(). So I don't know how to browse the rows in the database. Certainly my problem is in my foreach, but I don't find what's wrong.
Help please !
It seems your second foreach needs to be '$data' instead of $data['id_traitement']
So your code need to changed to ,
foreach($arr as $ligne_web)
{
foreach($data as $ligne_base) // <-- Here is the correction
{
if(($ligne_web[0] == $ligne_base) and ($flag))
{
------ REST of your Codes ------
Ok, I found an answer. Instead of an array $data from my database, and directly after the request, I created a new array.
Here is my code :
$conn_string = "host=localhost port=5432 dbname=test_postgre user=postgres password='1234'";
$dbconn = pg_connect($conn_string);
$sql = "SELECT id_traitement FROM public.traitement WHERE id_essai='.$id_essai.';";
$res = pg_query($sql) or die("Pb avec la requete: $sql");
$tableau_database_final = array();
while ($data = pg_fetch_all($res)) //Here is my array
{
$tableau_database = array('id_traitement'=>$data['id_traitement']);
array_push($tableau_database_final,$tableau_database);
}
$flag2 = true;
foreach($array as $ligne_web)
{
foreach($tableau_database_final as $ligne_base)
{
echo ($ligne_web[0]);
echo ($ligne_base);
if(($ligne_web[0] == $ligne_base)) //Si il existe une ligne ayant déjà le même id traitement
{
//update de la ligne
update_traitement($id_traitement,$traitement,$code_traitement,$id_essai);
$flag2 = false;
break 1;
}
}
if(($flag) && ($flag2))
{
//insert_traitement($id_traitement,$traitement,$code_traitement,$id_essai);
}
}
I have a problem with my function db_modif();. Everytime, if the value are correct and exist, the message is the first one (the if condition).
echo "Il n'y a aucun compte au nom de: ".$username." au site: ".$site." dans la base de données";
So, there is no modification in my Database
Here is my code form the manipulation :
<?php
$username = $_POST["user_search"];
$site = $_POST["adr_search"];
$fonction = $_POST["fonction"];
$modif = $_POST["modif_value"];
$prep ="";
if(!$username)
echo 'Nom d\'utilisateur manquant..';
elseif(!$site)
echo 'Site manquante..';
else{
require("db_action.php"); //Require in the database connection.
$bd = db_open(); // Open DATABASE
if($fonction == "usernameOp")
$prep = "username";
if($fonction == "adresseOp")
$prep = "adresse";
if($fonction == "passwdOp")
$prep = "password";
if($fonction == "siteOp")
$prep = "siteWeb";
if($fonction == "fonctionOp")
$prep = "fonction";
db_modif($prep, $username, $site, $modif);
db_close($bd);
}//ELSE
And from the function db_modif();:
function db_modif($prep, $username, $site, $modif){
error_reporting(-1); //Activer le rapport de toutes les genres d'erreurs
$querycon = "UPDATE info_compte SET $prep = '$modif' WHERE username = '$username' AND siteWeb = '$site'";
if($response = mysql_query($querycon) or trigger_error(mysql_error())){
echo "<pre>";
echo "Il n'y a aucun compte au nom de: <b>".$username."</b> au site: <b>".$site."</b> dans la base de données";
echo "</pre>";
}
else{
mysql_query($querycon);
echo "<pre>\n";
echo "Le compte <b>".$username."</b> du site : <b>".$site."</b> a été supprimé avec succès\n";
echo "</pre>";
}//ELSE
}//db_modif
Change AND WHERE to just AND on this line:
$querycon = "UPDATE info_compte SET $prep = '$modif'
WHERE username = '$username'
AND WHERE siteWeb = '$site'";
I'd suggest that you use mysql_error() to help debugging this sort of problem in future.
$response = mysql_query($querycon) or trigger_error(mysql_error());
You may also have an SQL injection vulnerability if any of those variables can contain quotes. Consider using mysql_real_escape_string or PDO with prepared statements.