PHP error while connecting to database - php

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.

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

SELECT COUNT * SQL PHP doesn't work

I have to search if a postal code is in my database, my table is called "test" there is only one table in my database with one column and one row, the column is named "codes", and there is an only row with the INT 63000, i have a form in my website where client enter a code, and it called a .php file which check if the value is missing or present in the database, i don't know PHP so it's hard for me... :( And my code don't work :(
SOLVED : THIS IS THE WORKING CODE :
<?php session_start(); ?>
<?php
if($_POST['code-postal'] === '') {
$hasError = true;
} else {
$variable = $_POST['code-postal'];
$code = intval($variable);
}
mysql_connect('xxxxxxxxx', 'xxxxxxxxxxxx', 'xxxxxxxxxxxx')
or die("I cannot connect to the database because: " . mysql_error());
mysql_select_db('xxxxxxxxxx');
$code = mysql_real_escape_string($code);
$sql = "SELECT COUNT(*) AS total_count FROM test WHERE codes='$code'";
$req = mysql_query($sql) or die('Erreur SQL !<br>'.$sql.'<br>'.mysql_error());
$data = mysql_fetch_assoc($req);
if($data['total_count'] == 1) {
$verif = true;
}
else {
$verif = false;
}
// on ferme la connexion à mysql
mysql_close();
?>
$sql = "SELECT COUNT(*) AS total_count FROM test WHERE codes='$code'";
$req = mysql_query($sql) or die('Erreur SQL !<br>'.$sql.'<br>'.mysql_error());
$data = mysql_fetch_assoc($req);
if($data['total_count'] == 1) {
$verif = true;
}
else {
$verif = false;
}
Here is the working code.
mysql_query would return result set. You will need to use mysql_fetch_assoc function to retrieve data from that.
I guess you would have more rows in table in future, because as you mentioned in table that you have only one table with one column and one row, then there is no need of database, you can directly compare values.

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

Check for specific entry in database

I want to check whether a specific entry is present in my database or not. If present then condition,if not then condition. I tried this code but got errors
<?php
$con=mysqli_connect("localhost","root","","student");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$classname = mysqli_real_escape_string($con, $_POST['class']);
$result = mysql_query("SELECT * FROM subjectinfo WHERE class = '{$classname}'", $con);
if(mysql_num_rows($result) == 0)
{
echo "No Such Entry In Table. Please ADD it First.";
}
else
{
echo "Entry Available";
}
}
mysqli_close($con);
?>
Errors :
Warning: mysql_query() expects parameter 2 to be resource, object given in C:\xampp\htdocs\pages\test.php on line 11
Warning: mysql_num_rows() expects parameter 1 to be resource, null given in C:\xampp\htdocs\pages\test.php on line 13
No Such Entry In Table. Please ADD it First.
Like your comments. Make sure you don't mix up mysqli and mysql. mysql is deprecated so you're better off using mysqli.
$con=mysqli_connect("localhost","root","","student");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$classname = mysqli_real_escape_string($con, $_POST['class']);
$result = mysqli_query($con, "SELECT * FROM subjectinfo WHERE class = '{$classname}'");
if(mysqli_num_rows($result) == 0)
{
echo "No Such Entry In Table. Please ADD it First.";
}
else
{
echo "Entry Available";
}
}
mysqli_close($con);
?>
You are mixing MySQL APIs - mysql_ + mysqli_ they do not mix together. Plus, your DB connection's backwards in your query. The connection comes first.
Here:
<?php
$con=mysqli_connect("localhost","root","","student");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$classname = mysqli_real_escape_string($con, $_POST['class']);
$result = mysqli_query($con,"SELECT * FROM subjectinfo WHERE class = '{$classname}'");
if(mysqli_num_rows($result) == 0)
{
echo "No Such Entry In Table. Please ADD it First.";
}
else
{
echo "Entry Available";
}
}
mysqli_close($con);
?>
Also use or die(mysqli_error($con)) to mysqli_query()
Plus, add error reporting to the top of your file(s) which will help during production testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
Look into using prepared statements, or PDO with prepared statements, they're safer.
An insight:
Make sure your form element is indeed named.
I.e.:
<input type="text" name="class">
otherwise, you will receive an Undefined index class... warning.

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.

Categories