pg_close() error? is a sub close closing the 2 connections? - php

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?

Related

PHP loop the INSERT MySQL for each result

I have already a script which scrapes all the urls of one csv with simple HTML dom.
The output is like this:
CoolerMaster Devastator II Azul
Coolbox DeepTeam - Combo teclado, ratón y alfombrilla
Asus Claymore RED - Teclado gaming
INSERT INTO productos (nombre) VALUES('Asus Claymore RED - Teclado gaming')
Items added to the database!
INSERT INTO productos (nombre) VALUES('Asus Claymore RED - Teclado gaming')
Items added to the database!
INSERT INTO productos (nombre) VALUES('Asus Claymore RED - Teclado gaming')
Items added to the database!
As you can see, the scrape contains 3 different products, but when I try to insert to the MySQL database, it only saves the last product --- but three times.
Here you can see my PHP Code for that:
<?php
require 'libs/simple_html_dom/simple_html_dom.php';
set_time_limit(0);
function scrapUrl($url)
{
$html = new simple_html_dom();
$html->load_file($url);
global $name;
$names = $html->find('h1');
foreach ($names as $name) {
echo $name->innertext;
echo '<br>';
}
$rutaCSV = 'csv/urls1.csv'; // Ruta del csv.
$csv = array_map('str_getcsv', file($rutaCSV));
foreach ($csv as $linea) {
$url = $linea[0];
scrapUrl($url);
}
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
foreach ($csv as $linea) {
$url = $linea[0];
$sql = "INSERT INTO productos (nombre) VALUES('$name->plaintext')";
print ("<p> $sql </p>");
if ($conn->query($sql) === TRUE) {
echo "Items added to the database!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
So, what I need is the MySQL query add:
INSERT INTO productos (nombre) VALUES('CoolerMaster Devastator II Azul')
Items added to the database!
INSERT INTO productos (nombre) VALUES('Coolbox DeepTeam - Combo teclado, ratón y alfombrilla')
Items added to the database!
INSERT INTO productos (nombre) VALUES('Asus Claymore RED - Teclado gaming')
Items added to the database!
You have a bunch of problems in your code.
First, you have function scrapUrl, that takes $url as an argument, but doesn't output anyhting. It's setting global $name variable, but, although it's find several names, it putting only the last one to the $name variable, because it's walking through a series of $names, put it's text into $name, and go for the next one, so, only last item is stored to your $name variable.
I would recommend, that your change your scrapUrl function, so it store names of scrapped products into an array, and return that array.
Second, I'm cannot understand how do you put your data into a csv file, the code, you've privided looks like it shouldn't work properly. Are you sure, that you are writing the right data in a csv file? Maybe here you are just reading data from file - in that case, I'm sorry.
The third: you are reading data from csv, and when moving line by line in the cycle, but the data is going nowhere. To my opinion, you should but $linea[0] into your SQL query, but you are putting $name->plaintext where, when $name is set only once in your scrapUrl, as I've mentioned above.
I would recommend, that you use the right variable in your SQL-query to pass data to it.
Also, it's better to use PDO and prepared statements instead of inserting raw data in your string-literals SQL queries.
Here is your code, just formatted: ( please check it you have a missing } )
function scrapUrl($url)
{
$html = new simple_html_dom();
$html->load_file($url);
global $name; // -- using global is crap - I would avoid that. Pass the object in as an argument of the function eg. scrapUrl($url, $name)
$names = $html->find('h1');
foreach ($names as $name) {
// -- your re-assigning $name overwriting you global on each iteration of this loop
// -- What is the purpose of this? it does nothing but output?
echo $name->innertext;
echo '<br>';
}
// -- missing } where is this function closed at?
$rutaCSV = 'csv/urls1.csv'; // Ruta del csv.
$csv = array_map('str_getcsv', file($rutaCSV));
foreach ($csv as $linea) {
// -- this can be combined with the one with the query
// -- just put the function call in that one and delete this one
$url = $linea[0];
scrapUrl($url); //recursive? depends where you function is closed
// -- whats the purpose of this function, it returns nothing?
}
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
foreach ($csv as $linea) {
$url = $linea[0]; // -- whats this url used for?
$sql = "INSERT INTO productos (nombre) VALUES('$name->plaintext')";
// -- query is vulnerable to SQL injection? prepared statement
// -- whats $name->plaintext? where is it assigned at?
print ("<p> $sql </p>");
if ($conn->query($sql) === TRUE) {
echo "Items added to the database!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// -- when you loop over the CSV but insert $name->plaintext multiple times
// -- where is that property changed inside this loop, how is it correlated to the csv data
}
$conn->close();
So first off you are missing a closing } Depending where that should be, depends on what else you have wrong.
One of you loops for the CSV can be eliminated ( maybe ), anyway I put bunch of notes in with comments like this // --
Your main issue, or the reason you inserts are the same is these lines
foreach ($csv as $linea) {
$url = $linea[0]; // -- whats this url used for?
$sql = "INSERT INTO productos (nombre) VALUES('$name->plaintext')";
// -- $name->plaintext does not change per iteration of the loop
// -- you are just repeatedly inserting that data
...
See you insert the value of $name->plaintext but this has no correlation to the $csv variable and you are not modifying it. It's no surprise it stays the same.
Ok, now that I picked apart your code ( nothing personal ). Let's see if we can simplify it a bit.
UPDATE This is the best I can do given the above code. I just combined it, fixed some logical errors, trimmed it down and simplified it. It's a common mistake of beginners to over-complicate the task. ( but there is no way for me to test this )
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$rutaCSV = 'csv/urls1.csv'; // Ruta del csv.
$csv = array_map('str_getcsv', file($rutaCSV));
//prepare query outside of the loops
$stmt = $conn->prepare("INSERT INTO productos (nombre)VALUES(?)");
foreach ($csv as $linea) {
//iterate over each csv line
$html = new simple_html_dom();
//load url $linea[0]
$html->load_file($linea[0]);
//find names in the document, and return them
foreach( $html->find('h1') as $name ){
//iterate over each name and bind elements text to the query
$stmt->bind_param('s', $name->plaintext);
if ($stmt->execute()){
echo "Items added to the database!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
There I further simplified it as it doesn't really make sense to have the function scrapUrl(). We're not re-using that code, so it adds a function call and makes the code harder to read by having it.
Even if it doesn't work strait away, I encourage you to compare the original code to what I have. And sort of walk through it in your mind, so you can get an feel for how I removed some of those redundancies etc.
For reference
mysqli prepare: http://php.net/manual/en/mysqli.prepare.php
mysqli bind_param: http://php.net/manual/en/mysqli-stmt.bind-param.php
mysqli execute: http://php.net/manual/en/mysqli-stmt.execute.php
Hope that helps, cheers!
Well, after been thinking about this for quite some time, I've managed to make it work.
I leave the code in case someone else can use it.
<?php
require 'libs/simple_html_dom/simple_html_dom.php';
set_time_limit(0);
function scrapUrl($url)
{
$html = new simple_html_dom();
$html->load_file($url);
global $name;
global $price;
global $manufacturer;
$result = array();
foreach($html->find('h1') as $name){
$result[] = $name->plaintext;
echo $name->plaintext;
echo '<br>';
}
foreach($html->find('h2') as $manufacturer){
$result[] = $manufacturer->plaintext;
echo $manufacturer->plaintext;
echo '<br>';
}
foreach($html->find('.our_price_display') as $price){
$result[] = $price->plaintext;
echo $price->plaintext;
echo '<br>';
}
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$price_go=str_replace(",",".",str_replace(" €","",$price->plaintext));
$sql = "INSERT INTO productos (nombre, nombreFabricante, precio) VALUES('$name->plaintext', '$manufacturer->plaintext', $price_go)";
print ("<p> $sql </p>");
if ($conn->query($sql) === TRUE) {
echo "Producto añadido al comparador!";
echo '<br>';
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
//echo $url;
}
$rutaCSV = 'csv/urls1.csv'; // Ruta del csv.
$csv = array_map('str_getcsv', file($rutaCSV));
//print_r($csv); // Verás que es un array donde cada elemento es array con una de las url.
foreach ($csv as $linea) {
$url = $linea[0];
scrapUrl($url);
}
?>
I'm pretty sure i have some trash in my code, but it works.
I hope it help for someone.
Regards and thanks for all the help.

PHP + Mssql Not Displaying Results

Connect to MSSQL
session_start();
// CONEXION
$link = mssql_connect('xxx.xxx.xx.xx', 'xxx', 'xxx');
mssql_select_db("xxx",$link);
if (!$link || !mssql_select_db('BDFlexline', $link)) {
die('No se puede conectar o seleccionar una base de datos!');
}
// FIN CONEXION
if( isset( $_GET["dcto"] ) ){
$dcto = $_GET["dcto"];
$empresa = $_GET['empresa'];
}
query here
$conn ="SELECT
D.TIPODOCTO, d.CORRELATIVO, d.CLIENTE,coalesce(c.razonsocial,'') RAZONSOCIAL,
v.DESCRIPCION as VENDEDOR , D.NUMERO, D.FECHA, D.TOTAL, d.Local as CLUB
from documento D
left join Vendedor v on d.Empresa = v.EMPRESA and d.Vendedor = v.CODIGO
left join ctacte c on c.empresa=d.empresa and c.tipoctacte=d.tipoctacte and c.ctacte =d.idctacte
where d.total >= 0
and d.aprobacion not in ('S','N')
and d.tipodocto='".$dcto."'
and d.empresa='".$empresa."'
and d.vigencia not in ('N','A')
and d.Fecha between CONVERT(VARCHAR(25), DATEADD(mm, -1, DATEADD(dd,-(DAY(GETDATE())-1),GETDATE())),105)
and CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(DATEADD(mm,1,GETDATE()))),DATEADD(mm,1,GETDATE())),105)
order by d.numero";
The query is ok, work as intended from within the SQL management console, but php ...
$result= mssql_query($conn, $link);
############# PRUEBA 1 #################
$json = array();
do {
while ($row = mssql_fetch_object($result)){
$json[] = $row;
}
}while ( mssql_next_result($result) );
echo json_encode($json);
mssql_close($link);
The result is [] but must be:
[{"TIPODOCTO":"COTIZACION","CORRELATIVO":"3059","CLIENTE":"20548547-2","RAZONSOCIAL":"SERVICIOS AIR LMTD","VENDEDOR":"Diana","NUMERO":"0000003079","FECHA":{"date":"2017-07-03 00:00:00.000000","timezone_type":3,"timezone":"Europe\/Berlin"},"TOTAL":"3111964.00000000","CLUB":"ADM"},
{"TIPODOCTO":"COTIZACION","CORRELATIVO":"3062","CLIENTE":"71540800-7","RAZONSOCIAL":"UNIVERSIDAD SAC","VENDEDOR":"Ernesto","NUMERO":"0000003482","FECHA":{"date":"2017-07-05 00:00:00.000000","timezone_type":3,"timezone":"Europe\/Berlin"},"TOTAL":"16670624.00000000","CLUB":"ADM"}] .... and more
I need the result in json format beacause im using angularJS.
Thanks for any idea
I am guessing that the values of $dcto or $empressa are wrong causing a blank result set. For a test do
echo "conn=$conn<br/>";
and see what shows on the screen. Then run that query in the console and make sure it gives you the results you want.

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;
}

Loop though database with foreach

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

How to create a SQL query in PHP with differents variables

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.

Categories