Why postgresql don't update query with php - php

i have a problem with a pg_query() on a php code.
When i send my request i have this error :
2015-02-10 16:57:16.793 Ambilly[658:191087] PHP Warning: pg_query(): in C:\inetpub\www.blabla.com\stoun\modifbati.php on line 22
this is my code :
<?php
session_start();
//On inclue les librairies
include('connect.php');
//on regarde si il y a eu un envoi ou non
if(isset($_POST['objectid'])&&isset($_POST['hauteur'])&&isset($_POST['occupation'])&&isset($_POST['nbr_niveau'])&&isset($_POST['nbr_lot'])&&isset($_POST['observation'])){
$codeID = $_POST['objectid'];
$hauteur = $_POST['hauteur'];
$occupation = $_POST['occupation'];
$nbrNiveau = $_POST['nbr_niveau'];
$nbrLot = $_POST['nbr_lot'];
$observation = $_POST['observation'];
//echo $code;
$conn = pg_pconnect("host=localhost port=5432 dbname=xxxxx user=xxxx password=xxxx");
if (!$conn) {
echo "An error occurred.\n";
exit;
}
//on fait le fichier
$date = date("Y-m-d");
$result = pg_query($conn, "UPDATE `suivi_bati` SET `hauteur`='".$hauteur."', `occupation`='".$occupation."', `nbr_niveau`='".$nbrNiveau."', `nbr_lot`='".$nbrLot."', `observation`='".$observation."' WHERE `objectid`='".$codeID."'");
if (!$result) {
echo "UPDATE IMPOSSIBLE";
echo pg_last_error();
exit;
} else {
echo "FICHE BATI MODIFIER";
}
}
else {
echo "Pas possible";
}
?>
Any idea ?
Thanks
Stoun

This query can't work:
$result = pg_query($conn, "UPDATE `suivi_bati` SET `hauteur`='".$hauteur."', `occupation`='".$occupation."', `nbr_niveau`='".$nbrNiveau."', `nbr_lot`='".$nbrLot."', `observation`='".$observation."' WHERE `objectid`='".$codeID."'");
because backquotes characters around identifiers are syntactically invalid in PostgreSQL. Remove them, the names used in this query (lower-case ASCII) don't need quotes anyway.
Also pg_escape_string needs to be applied to variables coming from a POST, otherwise your query is vulnerable to SQL injection.
The fixed query could look like this, with sprintf:
$result = pg_query($conn,
sprintf("UPDATE suivi_bati SET
hauteur='%s',
occupation='%s',
nbr_niveau='%s',
nbr_lot='%s',
observation='%s'
WHERE objectid='%s'",
pg_escape_string($hauteur),
pg_escape_string($occupation),
pg_escape_string($nbrNiveau),
pg_escape_string($nbrLot),
pg_escape_string($observation),
pg_escape_string($codeID))
);
or with the more modern pg_query_params, which doesn't need explicit escaping nor single quotes around literals:
$result = pg_query_params($conn,
"UPDATE suivi_bati SET
hauteur=$1,
occupation=$2,
nbr_niveau=$3,
nbr_lot=$4,
observation=$5
WHERE objectid=$6",
array($hauteur,
$occupation,
$nbrNiveau,
$nbrLot,
$observation,
$codeID)
);

Related

SQL command failed on the page execution

Just tested SQL command on phpmyadmin,it is successful.
But in the pages of php code, it is still an error occurred.
The error:
Erreur de syntaxe près de 'SELECT * FROM memberdata='david'' à la ligne 1
My connSQL php code:
<?php
$hostname_connSQL = "localhost";
$database_connSQL = "member";
$username_connSQL = "root";
$password_connSQL = "pooleasee";
$connSQL = mysqli_connect($hostname_connSQL, $username_connSQL, $password_connSQL) or die('Error:' .mysqli_error($connSQL));
mysqli_query($connSQL,"SET NAMES utf8")
?>
My login php code:
<?php
header("Content-Type: text/html; charset=utf-8");
require_once("connSQL.php");
session_start();
if(isset($_SESSION["m_username"]) && ($_SESSION["m_username"]!=""))
{
header("Location: membercenter.php");
}
if(isset($_POST["m_username"]) && isset($_POST["m_password"]))
{
$sql = "USE `member`; SELECT * FROM `memberdata`='".$_POST["m_username"]."'";
$RecLogin = mysqli_query($connSQL,$sql)or die('Error:' .mysqli_error($connSQL));
}
$row_RecLogin = mysqli_fetch_assoc($RecLogin);
$m_username = $row_RecLogin["m_username"];
$m_password = $row_RecLogin["m_password"];
if($_POST["m_password"]==$m_password)
{
$_SESSION["m_username"] = $m_username;
if(isset($_POST["rememberme"]) && ($_POST["rememberme"]=="true"))
{
setcookie("m_username", $_POST["m_username"], time()+365*24*60*60);
setcookie("m_password", $_POST["m_password"], time()+365*24*60*60);
} else
{
if(isset($_COOKIE["m_username"]))
{
setcookie("m_username", $_POST["m_username"], time()-100);
setcookie("m_password", $_POST["m_password"], time()-100);
}
}
{
header("Location: membercenter.php");
}
}
else
{
header("Location: index.php?loginFail=true");
}
?>
My database:
Actually I am a tiro,there are many places to learn.I couldn't find error.I hope you can help me.
Your query syntax is incorrect, WHERE columnName is missing. Also always escape the value with mysqli_real_escape_string
Incorrect Syntax:
$sql = "SELECT * FROM `memberdata`='".$_POST["m_username"]."'";
Correct Syntax:
$sql = "SELECT * FROM `memberdata` WHERE m_username='".mysqli_real_escape_string($connSQL, $_POST["m_username"])."'";
Change sql syntax to
$sql = "SELECT * FROM memberdata WHERE `m_username`='" . $_POST["m_username"] . "'";

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.

Why is mysql_num_rows() returning 0?

I have read in another threads that pasting the query in phpMyAdmin returns the amount of rows that you have, but in my case it doesn't even returns a value in phpMyAdmin, it's always 0! Here is the query:
$query = "SELECT nom_usu FROM usuarios WHERE nom_usu = '$usu' AND pass = '$pass';";
I open the .php file and run the query and it returns empty values, like this:
SELECT nom_usu FROM usuarios WHERE nom_usu = '' AND pass = '';
I also tried to echo the value that returns and is, guess what? Zero!
Here is the complete .php file (is for a login):
<?php
include('dbConfig.php');
$usu = $_POST["usu"];
$pass = $_POST["pass"];
$query = "SELECT nom_usu FROM usuarios WHERE nom_usu = '$usu' AND pass = '$pass';";
echo $query."\n";
if($resultado = mysql_query($query)){
if(mysql_num_rows($resultado) > 0){
echo mysql_num_rows($resultado);
echo "Todo está bien, no te preocupes :)";
echo true;
} else {
echo mysql_num_rows($resultado);
echo "Hay algo mal aquí :(";
}
} else {
echo false;
}
?>
And the dbConfig.php file:
<?php
$host="localhost";
$user="neosoftw_lambda";
$contra="myPass"; <- This is not actually my password...
$db="neosoftw_lambdaMovil";
$ms = mysql_connect($host, $user, $contra) or die("No se pudo conectar :(");
mysql_select_db($db, $ms) or die ("No hay base de datos :(");
?>
Hope someone can help me figure out where I have gone wrong?
Here is what I want to make, is a login in jQuery Mobile, but it doesn't work!
Username: bryan
Password: azul
http://android.neosoftware.org.mx/
Edit
Maybe it could be because of my javascript?
$.post("http://android.neosoftware.org.mx/PHP/login.php", {usu : usu, pass : pass}, function(respuesta_login){
if(!($("#txt_usuario").val() || $("#txt_password") == '')){
$.mobile.changePage("#campos_vacios");
} else {
if(respuesta_login == 1){
$("#txt_usuario").val('');
$("#txt_password").val('');
$.mobile.changePage("#pag_principal");
} else {
$.mobile.changePage("#error_login");
}
}
});
Use mysqli or PDO statements, as mysql is deprecated. Try this:
$usu = mysqli_real_escape_string($_POST["usu"]);
$pass = mysqli_real_escape_string($_POST["pass"]);
$query = "SELECT nom_usu FROM usuarios WHERE nom_usu = '".$usu."' AND pass = '".$pass."'";
And also your condition is incorrect.It should be like this:
if($resultado == mysqli_query($query)){
Try this query.
$query = "SELECT `nom_usu` FROM usuarios WHERE `nom_usu` = '".$usu."' AND `pass` = '".$pass."'";
Also this type of problem occurre when $_POST variable is empty.. So, double check your code.
Note : mysql_* function is deprecated, move on mysqli_* function asap.

PHP error while connecting to database

I'm trying to connect to a database that I created using this code:
<?php
function Conectarse()
{
$host="localhost";
$user="root";
$password="root";
$bda="toobebe_catalogo";
if (!($link=mysql_connect($host,$user,$password)))
{
echo "Error conectando a la base de datos.<br>";
exit();
}
else
{
echo "Éxito conectando con la base de datos.<br>";
}
if (!mysql_select_db($bda,$link))
{
echo "Error seleccionando la base de datos.<br>";
exit();
}
else
{
echo "Éxito al encontrar la base de datos.<br>";
}
return $link;
}
$conn=Conectarse();
$sql="SELECT * FROM toobebe-octubre";
$db_fila = mysql_query($sql,$conn);
$ok=1;
while (($row = mysql_fetch_array($db_fila)) && $ok)
{
$valor=mysql_query($sql,$conn);
if(!$valor)
{
$ok=0;
}
}
?>
But it fires this mistake when I execute it:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in ...
I've been searching, and to know:
- Database exists
Permissions are correct
Table exists
Table is not null
Any idea on why this mistake is happening?
EDIT:
Added image with the mistake:
The error isn't with connecting to the Database, but rather with your query. You have a hyphen in your table name, so you should try and enclose it as follows:
$sql = "SELECT * FROM `toobebe-octubre`";
$db_fila = mysql_query($sql, $conn);
$ok = 1;
while(($row = mysql_fetch_array($db_fila)) && $ok)
{
$valor=mysql_query($sql, $conn);
if(!$valor)
{
$ok=0;
}
}
Just a couple of tips, using mysql_* is severely deprecated now. You should really be using mysqli_* at a very minimum, or PDO.
Also, SELECT * is generally considered a bad practice, because I really doubt you do need everything from the table.

UPDATE password in mySQLDatabase with PHP

I am trying to update the password of the table 'nbk6_user'.
when the script is launched I get the error: "Fehler"
Am I doing the mysql_query right?
Can anybody help me please?
<?php
include 'conf.php';
$connection = mysql_connect("****", "****", "****");
mysql_select_db($datenbank);
session_start();
if(!isset($_SESSION["name"]))
{
die("Für diese Seite musst du dich zuerst anmelden!");
}
$name = $_SESSION["name"];
$pw1 = $_POST["pw1"];
$pw2 = $_POST["pw2"];
$pw1 = trim($pw1);
$pw2 = trim($pw2);
if($pw1 == "")
{
die("Kein Passwort gesetzt.");
}
if($pw1 == $pw2)
{
$query = mysql_query("UPDATE nbk6_user SET password='$pw1', WHERE name='$name'");
if(!$query)
{
echo "Fehler";
}
}
else
{
echo "Die Passwörter stimmen nicht überein";
}
?>
try see the error with mysql_error, but I think that u are putting "," after password='$pw1' I think so just try it
You shouldn't have a coma after SET and it's best to avoid inserting the variables inside a string, when dealing with MySQL queries (or any strings really, it's bad practice).
Try:
$query = mysql_query("UPDATE nbk6_user SET password='".$pw1."' WHERE name='".$name."'");
if(!$query)
{
mysql_error();
echo "Fehler";
}
if the changed query doesn't fix it mysql_error() will explain where the issue is.
You have a dangling comma:
... SET password='$pw1', WHERE ...
^---
Error in the query
use this
$query = mysql_query("UPDATE nbk6_user SET password='".$pw1."' WHERE name='".$name."'");
Also read the first answer here, this will brief you why you should not use mysql_* and use mysqli and PDO , taking care of sql injections.
At first :
session_start(); must be the first line in your code.
Then
$query = mysql_query("UPDATE nbk6_user SET password='$pw1', WHERE name='$name'");
must be
$pw1=md5($pw1);
$query = mysql_query("UPDATE nbk6_user SET password='$pw1' WHERE name='$name'");

Categories