Why is mysql_num_rows() returning 0? - php

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.

Related

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

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"] . "'";

Why postgresql don't update query with 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)
);

PHP MySQL query output

I am trying to do a query in which i can see if username and password can match. If it matches, then I will go to the administrator pages. The problem Im having is that i think that the query is not giving me the right results. The database table is called admin, and it has adminame and passadmin. The user im entering IS in the database. The password is encrypted.
<?php
$f_user = $_POST['f_user'];
$f_pass = $_POST['f_pass'];
$status = authenticate($f_user, $f_pass);
if ($status == 1)
{
include("../connections/config.php");
session_start();
//session_register("SESSION_UNAME");
$_SESSION['SESSION_UNAME'] = $f_user;
$SESSION_UNAME = $f_user;
header("Location: unoadmin.php");
exit();
}
else
{
$mensa= "Información Incorrecta...Inténtelo de Nuevo";
header("Location: register.php?mensa=$mensa");
exit();
}
function authenticate($user, $pass)
{
include("../connections/config.php");
$connection = mysql_connect($mach,$userna,$paso) or die ("Unable to connect!");
$query = "SELECT * from admin WHERE adminame = '$f_user'";
mysql_select_db($db);
$result = mysql_query($query, $connection) or die ("Error in query: $query. " . mysql_error());
$num_results = mysql_num_rows($result);
if ($num_results == 1)
{
for($i=0; $i < $num_results; $i++)
{
$row = mysql_fetch_array($result);
$pas = $row["passadmin"];
}
if(crypt($pass,$pas) == $pas)
{
return 1;
}
else
{
return 0;
}
}
else
{
return 0;
}
}
?>
Can someone tell me what is the error? It is leading me to "Información incorrecta. Intentelo de nuevo" or in english "Wrong information. Try again"
It is a bit of a guess, but your authenticate function returns false (error message)
I am not sure what happens in the include, it suggests inclusion of database settings.
You are using 2 different vars for the username: is:
function authenticate($user, $pass) // <-- you pass $user
{
include("../connections/config.php");
$connection = mysql_connect($mach,$userna,$paso) or die ("Unable to connect!");
$query =
"SELECT * from admin WHERE adminame = '$f_user'"; // <-- you use $f_user
Perhaps not a real answer, but it was to long for a comment.
A simple solution of this question is to put your user name and password in variables and match it with database, If result have greater than 1 value than it will go to admin page. For example
$myusername=addslashes($_POST['username']);
$mypassword=addslashes($_POST['password']);
$sql="SELECT * FROM admin WHERE username='$myusername' and password=md5('$mypassword')";
$query = mysql_query($sql);
$row = mysql_num_rows($query);
if($row>0) {
header("location:administrator.php");
}
else {
echo"Please check username and password";
}
From your code you have either:
no such entry in your DB with the username you provided
the password is wrong
Furthermore you should check your code for SQL injections!
Please take time to read article below,
Best Way to prevent SQL Injection in PHP

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