My php code loops and doesn't explore my database [duplicate] - php

This question already has answers here:
The 3 different equals
(5 answers)
Closed 1 year ago.
Hello I'm currently trying to create a page based on a database under mysql that would update itself for a client. However what I'm trying to do loops and returns the first value of the database each time and indefinetely when I want it to go on to another object in the database. Here is the code, I'm a beginner so the error might be flagrant, thanks for the help.
<?php
try
{
$db = new PDO('mysql:host=localhost;dbname=labase', 'root' ,'');
$db->exec(" SET CHARACTER SET utf8 ");
$db->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e){
echo'une erreur est survenue';
die();
}
for ($i = 1; $i < 10; $i++) {
if ($i=1){
$select = $db->prepare("Select profession from contact where affiliation='nord' group by profession"); // je récupère les professions de la bdd
$select->execute();
}
$data = $select->fetch(PDO::FETCH_OBJ);
$profess=$data->profession; // je prends la prochaine profession
$selectionner = $db->prepare("Select nomcontact, count(*) as nbrcontact from contact where affiliation='nord' and profession='$profess'"); // je prends les contacts qui ont cette profession ainsi que leur nombre
$selectionner->execute();
$prendre = $selectionner->fetch(PDO::FETCH_OBJ);
$nbrcontact=$prendre->nbrcontact;// je récupère leur nombre
echo $profess;
echo $nbrcontact;
}
?>

I am not a PHP expert and never use PDO, but in Msqli, there is a fetch_array() to get multiple result (instead of fetch for single result), maybe in PDO you have a fetch_array too. Then, you can loop on the result array
Something like that (using msqli)
$sql = "SELECT... FROM ..";
$result = $link->query($sql);
while($row =mysqli_fetch_array($result))
{
}

if ($i=1) { // here is should be == or ===

You're causing an infinite loop by declaring $i=1
<?php
try
{
$db = new PDO('mysql:host=localhost;dbname=labase', 'root' ,'');
$db->exec(" SET CHARACTER SET utf8 ");
$db->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e){
echo'une erreur est survenue';
die();
}
for ($i = 1; $i < 10; $i++) {
if ($i == 1){ // added code
$select = $db->prepare("Select profession from contact where affiliation='nord' group by profession"); // je récupère les professions de la bdd
$select->execute();
}
$data = $select->fetch(PDO::FETCH_OBJ);
$profess=$data->profession; // je prends la prochaine profession
$selectionner = $db->prepare("Select nomcontact, count(*) as nbrcontact from contact where affiliation='nord' and profession='$profess'"); // je prends les contacts qui ont cette profession ainsi que leur nombre
$selectionner->execute();
$prendre = $selectionner->fetch(PDO::FETCH_OBJ);
$nbrcontact=$prendre->nbrcontact;// je récupère leur nombre
echo $profess;
echo $nbrcontact;
}
?>
Use == for comparison

Related

Issue Updating date with Oracle and PHP

Im doing a Crud with PHP and Oracle, adding the info and deleting the info works fine. But Updating is not saving on the oracle database. Im sure that is something related to the DATE format, because I had the same project with other database and doesnt have any problem. Any guess, whats it happening?
<?php
require_once 'conexion.php';
$idautor = $_POST['ID_AUTOR'];
$nameautor = $_POST['NOMBRE_AUTOR'];
$bdate = date("m-d-Y", strtotime($_POST['FECHA_NACIMIENTO']));
$query = "UPDATE AUTOR SET NOMBRE_AUTOR ='".$nameautor."', FECHA_NACIMIENTO ='".$bdate."' WHERE ID_AUTOR = '".$idautor."' ";
// $query = "UPDATE AUTOR SET NOMBRE_AUTOR ='".$nameautor."' WHERE ID_AUTOR = '".$idautor."' ";
$statement = oci_parse($conexion,$query);
$r = oci_execute($statement,OCI_DEFAULT);
$res = oci_commit($conexion);
if ($res) {
// Mensaje si los datos cambian
echo "<script>alert('Los libros se actualizaron con exito'); window.location.href='sistema.php'</script>";
header('Location: sistema.php');
} else {
// Mensaje si los datos no cambian
echo "<script>alert('Los datos no se pudieron actualizar'); window.location.href='sistema.php'</script>";
// echo oci_error();
}
} else {
// si intenta acceder directamente a esta página, será redirigido a la página de índice
header('Location: sistema.php');
}
Your code is an open door for SQL-Injection. It should be like this:
$query = "UPDATE AUTOR SET
NOMBRE_AUTOR = :nameautor, FECHA_NACIMIENTO = TO_DATE(:bdate, 'YYYY-MM-DD')
WHERE ID_AUTOR = :idautor";
$statement = oci_parse($conexion, $query);
oci_bind_by_name($statement, ':nameautor', $nameautor, 1000, SQLT_CHR);
oci_bind_by_name($statement, ':bdate', date_format($bdate, 'Y-m-d'), 30, SQLT_CHR);
oci_bind_by_name($statement, ':idautor', $idautor, 100, SQLT_INT);
$r = oci_execute($statement, OCI_DEFAULT);
You have to use TO_DATE(...), because type like SQLT_DATE does not exist. Otherwise you rely on current session NLS_DATE_FORMAT which may change at any time.

How to count result [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I don't know much about PHP and I came on a problem, how to be able to display the number of results.
Example: 'There are 200 results'.
Thank you in advance.
Attached is my code
try
{
$bdd = new PDO("mysql:host=localhost;dbname=pdf", "root", "");
$bdd ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e)
{
die("Une érreur a été trouvé : " . $e->getMessage());
}
$bdd->query("SET NAMES UTF8");
if (isset($_GET["s"]) AND $_GET["s"] == "Rechercher")
{
$_GET["terme"] = htmlspecialchars($_GET["terme"]); //pour sécuriser le formulaire contre les intrusions html
$terme = $_GET["terme"];
$terme = trim($terme); //pour supprimer les espaces dans la requête de l'internaute
$terme = strip_tags($terme); //pour supprimer les balises html dans la requête
if (isset($terme))
{
$terme = strtolower($terme);
$select_terme = $bdd->prepare("SELECT titre, description, lien, lien_image FROM bdr WHERE titre LIKE ? OR description LIKE ?");
$select_terme->execute(array("%".$terme."%", "%".$terme."%"));
}
else
{
$message = "Vous devez entrer votre requete dans la barre de recherche";
}
}
while($terme_trouve = $select_terme->fetch())
{
...
}
$select_terme->closeCursor();
?>
There are few approaches:
1. use $counter and increase it
$counter=0;
while($terme_trouve = $select_terme->fetch())
{
...
$counter++;
}
echo "cnt=".$counter;
2. Use a second sql and get count directly
$select_terme = $bdd->prepare("SELECT count(1) as cnt FROM bdr WHERE titre LIKE ? OR description LIKE ?");
3. use a build in function with initial sql to count
$rowcount=mysqli_num_rows($result_query);
or depend how connection is obtained (above case)
$rowcount = $select_terme->rowCount();
or
$rowcount = $select_terme->fetchColumn();
(count on select)

how to do and show results of 2 subqueries in php web services and generate a json encode

I'm doing a web service but I need to get data from two different tables taking into account the result of a query in a relational table
How can I make 2 queries to two different tables taking into account a 3 query to obtain the data of those queries?
I have a relational table in which I keep the id's and I need to make a query of that table and then make two queries to two different tables to get the data and show them together in a json to be able to use it
example:
$ query1 = "select * from family where ID = 2";
while ($ query1) {
$ consult2 = "select * from adults where son = $ query1 ['ID']";
$ consult3 = "select * from siblings where son = $ query1 ['ID']";
}
my code for the query is this, is in PHP:
require 'Database.php';
class Union {
function __construct(){
}
public static function getById($id_vehiculo){
// Consulta del vehiculo
$consulta = "SELECT id_relacion, id_operador, id_vehiculo FROM uniontaxioperador WHERE id_vehiculo = ?";
try {
// Preparar sentencia
$comando = Database::getInstance()->getDb()->prepare($consulta);
// Ejecutar sentencia preparada
$comando->execute(array($id_vehiculo));
// Capturar primera fila del resultado
$row = $comando->fetch(PDO::FETCH_ASSOC);
return $row;
} catch (PDOException $e) {
// Aquí puedes clasificar el error dependiendo de la excepción
// para presentarlo en la respuesta Json
return -1;
}
}
}
and to show the json is this:
require 'WS_consulta.php';
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
if (isset($_GET['id_vehiculo'])) {
// Obtener parámetro id_vehiculo
$parametro = $_GET['id_vehiculo'];
// Tratar retorno
$retorno = Union::getById($parametro);
if ($retorno) {
$union["estado"] = "1";
$union["id_relacion"] = $retorno;
// Enviar objeto json de la union
print json_encode($union);
} else {
// Enviar respuesta de error general
print json_encode(
array(
'estado' => '2',
'mensaje' => 'No se obtuvo el registro'
)
);
}
} else {
// Enviar respuesta de error
print json_encode(
array(
'estado' => '3',
'mensaje' => 'Se necesita un identificador'
)
);
}
}

mysql_query() error (Invalid Query) in a searcher php [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
this is a searcher program php with MySqL this give me a error, and i need a bit help on this...
This is the php Code:
<?php
if ($_POST['buscar'])
{
// Tomamos el valor ingresado
$buscar = $_POST['palabra'];
// Si está vacío, lo informamos, sino realizamos la búsqueda
if(empty($buscar))
{
echo "No se ha ingresado una cadena a buscar";
}else{
//Conexión a la base de datos
$servidor = "localhost"; //Nombre del servidor
$usuario = "root"; //Nombre de usuario en tu servidor
$password = "1234"; //Contraseña del usuario
$base = "db_maquinas"; //Nombre de la BD
$con = mysql_connect($servidor, $usuario, $password) or die("Error al conectarse al servidor");
mysql_select_db($base, $con) or die("Error al conectarse a la base de datos");
$sql= mysql_query("SELECT * FROM repuestos WHERE id LIKE '%$buscar%' AND descripcion LIKE '%$buscar%' ORDER BY id", $con) or die(mysql_error($con));
$result = mysql_query($sql, $con); //<----LINE 32!!!
// Tomamos el total de los resultados
if($result) { $total = mysql_num_rows($result); } else { die('Invalid query' . mysql_error($con)); }
echo "<table border = '1'> \n";
//Mostramos los nombres de las tablas
echo "<tr> \n";
while ($field = mysql_fetch_field($result)){
echo "<td>$field->name</td> \n";
}
echo "</tr> \n";
do {
echo "<tr> \n";
echo "<td>".$row["id"]."</td> \n";
echo "<td>".$row["descripcion"]."</td> \n";
echo "<td>".$row["cantidad"]."</td> \n";
echo "</tr> \n";
} while ($row = mysql_fetch_array($result));
echo "</table> \n";
echo "¡ No se ha encontrado ningún registro !";
}
}
?>
The error is --> Warning: mysql_query() expects parameter 1 to be string, resource given in C:\xampp\htdocs\maquinas2000\paginas\buscarepuestos.php on line 32
Invalid query {Line 32 is -> $result = mysql_query($sql, $con); }
i work with a Localhost xampp ofc, this give me a lot of troubles this code, i need only this and i'll finish 100% the work, so if anyone can give me the answer of this error i'll be very grateful for that, thx!
You have already executed the query. mysql_query return true or false and you are passing this return value again in mysql_query , make changes this :
$sql= "SELECT * FROM repuestos WHERE id LIKE '%$buscar%' AND descripcion LIKE '%$buscar%' ORDER BY id";// remove mysql_query from this line
$result = mysql_query($sql, $con);
Important : mysql_ is depricated use mysqli instead of that

PHP & SQL problem

I have a problem with my function db_modif();. Everytime, if the value are correct and exist, the message is the first one (the if condition).
echo "Il n'y a aucun compte au nom de: ".$username." au site: ".$site." dans la base de données";
So, there is no modification in my Database
Here is my code form the manipulation :
<?php
$username = $_POST["user_search"];
$site = $_POST["adr_search"];
$fonction = $_POST["fonction"];
$modif = $_POST["modif_value"];
$prep ="";
if(!$username)
echo 'Nom d\'utilisateur manquant..';
elseif(!$site)
echo 'Site manquante..';
else{
require("db_action.php"); //Require in the database connection.
$bd = db_open(); // Open DATABASE
if($fonction == "usernameOp")
$prep = "username";
if($fonction == "adresseOp")
$prep = "adresse";
if($fonction == "passwdOp")
$prep = "password";
if($fonction == "siteOp")
$prep = "siteWeb";
if($fonction == "fonctionOp")
$prep = "fonction";
db_modif($prep, $username, $site, $modif);
db_close($bd);
}//ELSE
And from the function db_modif();:
function db_modif($prep, $username, $site, $modif){
error_reporting(-1); //Activer le rapport de toutes les genres d'erreurs
$querycon = "UPDATE info_compte SET $prep = '$modif' WHERE username = '$username' AND siteWeb = '$site'";
if($response = mysql_query($querycon) or trigger_error(mysql_error())){
echo "<pre>";
echo "Il n'y a aucun compte au nom de: <b>".$username."</b> au site: <b>".$site."</b> dans la base de données";
echo "</pre>";
}
else{
mysql_query($querycon);
echo "<pre>\n";
echo "Le compte <b>".$username."</b> du site : <b>".$site."</b> a été supprimé avec succès\n";
echo "</pre>";
}//ELSE
}//db_modif
Change AND WHERE to just AND on this line:
$querycon = "UPDATE info_compte SET $prep = '$modif'
WHERE username = '$username'
AND WHERE siteWeb = '$site'";
I'd suggest that you use mysql_error() to help debugging this sort of problem in future.
$response = mysql_query($querycon) or trigger_error(mysql_error());
You may also have an SQL injection vulnerability if any of those variables can contain quotes. Consider using mysql_real_escape_string or PDO with prepared statements.

Categories