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);
}
}
Related
I'm trying to understand functions. I created a function and i want to call it multiple times. First I do a SQL query, save it in an array and convert it to seconds. The next thing is do a new SQL query (which does his job perfectly fine). When I try to convert this to seconds it goes wrong, I get this error:
Cannot redeclare myfunction() (previously declared in C:\xampp\htdocs\webpagina met input - kopie\try.php:103) in C:\xampp\htdocs\webpagina met input - kopie\try.php on line 103.
Can anyone help?
<?php
$servername = "localhost"; //inloggegevens database
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
// check of er nog genoeg tijd over is en vergelijk met ingevoerde tijd
$sql1 = "SELECT tijd FROM gespeeldeTijd"; // get data with sql query
sqlquery($sql1, $conn, "tijd");
if ($stateLoop == "1") {
convertArrayToMHS($myArray);
hsmToSeconds($sumUren, $sumMinuten, $sumSeconden);
print_r($seconden);
$myArray = [];
$stateLoop == "0";
$sql2 = "SELECT tijd FROM toegelatentijd WHERE naam = 'thomas'"; // get data with sql query
sqlquery($sql2, $conn, "tijd");
if ($stateLoop == "1") {
convertArrayToMHS($myArray);
hsmToSeconds($sumUren, $sumMinuten, $sumSeconden);
print_r($seconden);
$myArray = [];
$stateLoop == "0";
}
} else {
}
// check of er nog een tijd loopt
$sql1 = "SELECT stopTijd FROM gespeeldeTijd ORDER BY ID DESC LIMIT 1"; // get data with sql query
sqlquery($sql1, $conn, "stopTijd");
if ($stateLoop == "1") {
/* print_r($myArray); */
// get time now an compare these to the time asked in sql 1, if time is still not reached get time and display, if time is reached show input field
} else {
}
}
function sqlquery($sql, $conn, $naamtabel) {
global $myArray;
global $stateLoop;
$stateLoop = "0";
$result = $conn->query($sql);
if ($result->num_rows > 0) { // do a while loop to fetch all data to an array
// output data of each row
while ($row = $result->fetch_assoc()) {
$myArray[] = $row["$naamtabel"]; //alle data van kolom "tijd" in een array
/* print_r($myArray); */
}
$stateLoop = "1";
} else { // if there are no results
echo "0 results";
}
}
function convertArrayToMHS($myArray) {
global $sumUren;
global $sumMinuten;
global $sumSeconden;
global $array_product;
function myfunction($value) { //function to do to evry part of the array
global $array_product;
$array_product[] = explode(":", $value); // split the time in hours, minutes, seconds
return $array_product; //bevat alle gesplitte waardes
}
array_walk($myArray, "myfunction"); // walk trough evry part of the array en voer er "myfunction" op uit
/* print_r($array_product); */
/* print_r($totalElements); */
$uren = array_column($array_product, '0'); // zet alle waarden in een aparte array met 0 (uren)
$minuten = array_column($array_product, '1'); // zet alle waarden in een aparte array met 0 (uren)
$seconden = array_column($array_product, '2'); // zet alle waarden in een aparte array met 0 (uren)
$sumUren = 0;
$sumMinuten = 0;
$sumSeconden = 0;
foreach ($uren as $uren) { //tel alle uren van de sql database bijeen
$sumUren = $sumUren + $uren;
}
foreach ($minuten as $minuten) { //tel alle minuten van de sql database bijeen
$sumMinuten = $sumMinuten + $minuten;
}
foreach ($seconden as $seconden) { //tel alle seconden van de sql database bijeen
$sumSeconden = $sumSeconden + $seconden;
}
}
function hsmToSeconds($sumUren, $sumMinuten, $sumSeconden) {
global $seconden;
$seconden = ($sumUren * 3600) + ($sumMinuten * 60) + $sumSeconden; //uren/minuten/seconden omzetten naar seconden
}
?>
You call to convertArrayToMHS twice, every call you declare myfunction.
Put myFunction outside of convertArrayToMHS.
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'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);
?>
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.
I am currently getting this error: pg_close(): 12 is not a valid PostgreSQL link resource. This is the code that is being executed:
function getProyectosDeUsuarioDAO($idUsuario)
{
$conexion = conectar();
$consulta = "sql things here;";
$resultado = pg_query($consulta) or die('Consulta fallida: ' . pg_last_error());
$lista = array();
$lista = pg_fetch_all($resultado);
var_dump($lista);
$listaProyectos = array();
if(!empty ($lista))
{
foreach ($lista as $p)
{
$proyecto = new Proyecto();
$proyecto->setNombre($p['nombre']);
$proyecto->setFechaInicio($p['fechainicio']);
$proyecto->setFechaFin($p['fechafin']);
$proyecto->setId($p['id']);
//Cargar roles del usuario para cada proyecto
$proyecto->setRoles(getRolesByProyecto($proyecto->getId(),$idUsuario));
array_push($listaProyectos, $proyecto) ;
}
if($conexion)
{
pg_close($conexion); //##############error here#################
}
pg_free_result($resultado);
var_dump($listaProyectos);
return $listaProyectos;
}
var_dumps are made to check if the query is working and it does work; I am not sure how to debug this.
I am using php_pgsql and WAMP server
($conexion) works for checking, however I'm not sure if connection is live or not?