Update not performed - php

I prepare a script which update the field "stock" in the database of my online shop.
When I run it ther's no No errors who appears ! However no change occurs at the database
So what can be the problem ! It can't access to the database because of it's name ?
Any idea?
Here is the code below :
<?php
/*---------------------CONNEXION MYSQL----------------------*/
$servername='';
$database_username='';
$database_password='';
$database_name='';
set_time_limit(1600);
$link = mysql_connect($servername, $database_username, $database_password);
//$link = mysql_connect('mysql5-6.240', 'vintagemvm75', 'pu1df4mu');
if (!$link) {
die('Connexion impossible : ' . mysql_error());
}
echo 'Connecté correctement';
//$link = mysql_connect($servername,$database_username,$database_password) or die("Erreur de connexion au serveur"); //mysql_connect
//mysql_select_db($link, $database_name) or die("Erreur de connexion à la BDD"); //old: mysql_select_db
/*---------------------FIN CONNEXION MYSQL----------------------*/
/*---------------------RÉCUPÉRATION DU FICHIER STOCK et INITIALISATION----------------------*/
$fichier = file("../batch/export_solsys.csv");
$fp = fopen("../batch/export_solsys.csv","r");
$upc= "";
$stock="";
$ligne = 1;
/*---------------------FIN RÉCUP----------------------*/
echo("Parcours du fichier...")."<br/>";
/*---------------------MISE A JOUR DU STOCK----------------------*/
while($tab=fgetcsv($fp,1000,';'))
{
$champs = count($tab);//nombre de champs dans la ligne en question
$ligne++;
$upc = $tab[0];
$stock = $tab[7];
echo("upc: ").$upc."<br/>";
echo("stock: ").$stock."<br/>";
$batch = "SELECT stock FROM declinaison_stock_produit where upc = '56939'";
$requete = mysql_query($batch, $link);
$batch1 ="UPDATE declinaison_stock_produit SET stock = '4' where upc = '56939'";
$requete1 = mysql_query($batch1, $link);
echo("Stock mis à jour ");
echo("Fin de l'éxécution du batch");
}
?>

You have not filled out your connection variables that are being passed to mysql_connect.
Moreover, you are not even using mysql_select_db(), to connect to database. It should be something like:
mysqli_select_db($link, $database_name);
Otherwise, provide the database name in mysql_connect() in the following manner:
$link = mysql_connect($servername, $database_username, $database_password, $database_name);
You need to have these variables filled out in order to connect to the database:
$servername='';
$database_username='';
$database_password='';
$database_name='';
You have commented out the lines where you hard-coded them.

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.

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

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

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

no database selected php/mysql

i have a trouble with this T_T this is a searching/consult script for cars parts
this is the php
<?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");
$sql= mysql_query("SELECT * FROM repuestos WHERE 'id','descripcion' LIKE '%$buscar%' ORDER BY id", $con) or die(mysql_error($con));
mysql_select_db($base, $con) or die("Error al conectarse a la base de datos");
$result = mysql_query($sql, $con);
// 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 !";
}
}
?>
that when on the form i press "Send or Search" this send me to another page that says "NO DATABASE SELECTED"
I hope somebody can help me with that..
PD: i'm using a localhost DB with PhpMyAdmin i have items on tables, i verified tables not empty...
You select your database after you attempt to run queries. Place the code before you attempt to run queries:
mysql_select_db($base, $con) or die("Error al conectarse a la base de datos");
$sql= mysql_query("SELECT * FROM repuestos WHERE 'id','descripcion' LIKE '%$buscar%' ORDER BY id", $con) or die(mysql_error($con));
FYI, you shouldn't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
place the mysql_selectdb() before the mysql_query().

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