I am having an error when inserting data into a table with php using prepared statements, I am stuck cuz it gives me errno(0), I dont know what that error is, can you help me please?. Thanks!
<?php
session_start();
include '../conexion.php';
$nombre = $_POST['Nombre'];
$apellido = $_POST['Apellido'];
$mail = $_POST['Mail'];
$telefono = $_POST['Telefono'];
$ultimaventa = $_POST['Numeroventa'];
$totalcomprado = 0;
$ultimomonto = $_POST['Total'];
if($cons = $mysqli->prepare("select 1 from clientes WHERE Mail=?"));
$cons->bind_param('s',$mail);
$cons->execute();
$cons->store_result();
$existe=$cons->num_rows > 0;
if ($existe) {
$totalcomprado=totalcomprado+$ultimomonto;
if(!($cons=$mysqli->prepare("UPDATE clientes SET nombre=?,apellido=?,Mail=?,telefono=?,ultimaventa=?,ultimomonto=?,totalcomprado= ? WHERE Mail=?"))){
echo "fallo en la preparacion de la consulta:(".$mysqli->errno.")" .$mysqli->error;
}
$cons->bind_param('sssssiis',$nombre,$apellido,$mail,$telefono,$ultimaventa,$totalcomprado,$mail);
if(!($cons->execute())){
echo "fallo ejecutando la consulta:(".$mysqli->errno.")" .$mysqli->error;
}
$cons->close;
} else {
$totalcomprado=$ultimomonto;
if(!($cons=$mysqli->prepare("INSERT into clientes id,nombre,apellido,Mail,telefono,ultimaventa,ultimomonto,totalcomprado values(?,?,?,?,?,?,?)"))){
echo "fallo en la preparacion de la consulta:(".$mysqli->errno.")" .$mysqli->error;
}
$cons->bind_param('sssssis',$nombre,$apellido,$mail,$telefono,$ultimaventa,$totalcomprado);
if(!($cons->execute())){
echo "fallo ejecutando la consulta:(".$mysqli->errno.")" .$mysqli->error;
}
}
Ps.: The data types to insert are ok, the only one Integer is "ultimomonto"
This is the error:
fallo en la preparacion de la consulta:(0)
( ! ) Fatal error: Call to a member function bind_param() on a non-object in C:\wamp\www\mumushop\compras\verificar.php on line 35
You're missing the parentheses arount the column names in the INSERT statement:
if(!($cons=$mysqli->prepare("INSERT into clientes (id,nombre,apellido,Mail,telefono,ultimaventa,ultimomonto,totalcomprado) values(?,?,?,?,?,?,?)"))){
There's another problem that isn't related to the error:
if($cons = $mysqli->prepare("select 1 from clientes WHERE Mail=?"));
The ; ends this if statement, so you're not using it to execute anything based on whether this is successful. I think you want all the rest of the code to be inside this, so it should be:
if($cons = $mysqli->prepare("select 1 from clientes WHERE Mail=?")) {
$cons->bind_param('s',$mail);
$cons->execute();
$cons->store_result();
$existe=$cons->num_rows > 0;
if ($existe) {
...
} else {
...
}
}
The undefined constant error is coming from this line:
$totalcomprado=totalcomprado+$ultimomonto;
You're missing the $ before totalcomprado, it should be:
$totalcomprado=$totalcomprado+$ultimomonto;
or you can write it as:
$totalcomprado += $ultimomonto;
Related
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
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'
)
);
}
}
After changing this query to be user with binding parameters, It won't work anymore.
$conectar2 = mysqli_connect(HOST, USER, PASS, DATABASE);
$buscarUsuarioExistente = " SELECT userID, userEmail
FROM usuarios
WHERE userEmail =?
";
$usuarioExiste = mysqli_prepare($conectar2,$buscarUsuarioExistente);
mysqli_stmt_bind_param($usuarioExiste, 's', $email);
mysqli_stmt_execute($usuarioExiste);
mysqli_stmt_close($usuarioExiste);
//SI EL MAIL QUE PONE EL USUARIO YA EXISTE EN BASE
if (mysqli_stmt_affected_rows($usuarioExiste) != 0) {
$usuario = mysqli_fetch_assoc($usuarioExiste);
//como nos devuelve un array, extraemos el primer elemento como string. El array contiene sólo un elemento.
$userID = array_shift($usuario);
//si el usuario existe en base, no lo generamos, sino que le agregamos el curso que seleccionó y le asignamos el rol "noAutorizado" hasta no verificar el pago
$asignarRol = "INSERT INTO rolesUsuarios
(userID, nombreRol)
VALUES
(?, ?)
";
$noAutorizado = 'noAutorizado';
$asignarRolenBase = mysqli_prepare($conectar2,$asignarRol);
mysqli_stmt_bind_param($asignarRolenBase, 'ss', $userID, $noAutorizado);
mysqli_stmt_execute($asignarRolenBase);
if ($asignarRolenBase) {
echo 'Estado "pendiente" del usuario generado.<br>';
}
else {
echo 'Error al asignar estado al usuario'.mysqli_error($conectar2).'<br>';
}
mysqli_stmt_close($asignarRolenBase);
}
The problem seems to be with this: mysqli_stmt_affected_rows($usuarioExiste) != 0 (this is line 45)
Because I get this error:
Warning: mysqli_stmt_affected_rows(): Couldn't fetch mysqli_stmt in
/home/public_html/inscripcionUsuario.php on line 45
UPDATE:
I've noticed that I do close it in the line before I call it (thanks Qirel), but moving further down that line, so I don't close it before, gives me this error:
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result,
object given
So, with the update:
$conectar2 = mysqli_connect(HOST, USER, PASS, DATABASE);
$buscarUsuarioExistente = " SELECT userID, userEmail
FROM usuarios
WHERE userEmail =?
";
$usuarioExiste = mysqli_prepare($conectar2,$buscarUsuarioExistente);
mysqli_stmt_bind_param($usuarioExiste, 's', $email);
mysqli_stmt_execute($usuarioExiste);
//SI EL MAIL QUE PONE EL USUARIO YA EXISTE EN BASE
if (mysqli_stmt_affected_rows($usuarioExiste) != 0) {
$usuario = mysqli_fetch_assoc($usuarioExiste);
//como nos devuelve un array, extraemos el primer elemento como string. El array contiene sólo un elemento.
$userID = array_shift($usuario);
//si el usuario existe en base, no lo generamos, sino que le agregamos el curso que seleccionó y le asignamos el rol "noAutorizado" hasta no verificar el pago
$asignarRol = "INSERT INTO rolesUsuarios
(userID, nombreRol)
VALUES
(?, ?)
";
$noAutorizado = 'noAutorizado';
$asignarRolenBase = mysqli_prepare($conectar2,$asignarRol);
mysqli_stmt_bind_param($asignarRolenBase, 'ss', $userID, $noAutorizado);
mysqli_stmt_execute($asignarRolenBase);
if ($asignarRolenBase) {
echo 'Estado "pendiente" del usuario generado.<br>';
}
else {
echo 'Error al asignar estado al usuario'.mysqli_error($conectar2).'<br>';
}
mysqli_stmt_close($asignarRolenBase);
mysqli_stmt_close($usuarioExiste);
}
Update:
I've tried with mysqli_stmt_num_rows()
(if (mysqli_stmt_num_rows($usuarioExiste) != 0))
Instead and I've got this error:
Warning: mysqli_stmt_bind_param() expects parameter 1 to be
mysqli_stmt, boolean given
Your problem is here
mysqli_stmt_close($usuarioExiste);
You're closing the mysqli_stmt object which does
Closes a prepared statement. mysqli_stmt_close() also deallocates the statement handle
As to the other question, you're missing a step
$usuario = mysqli_fetch_assoc($usuarioExiste);
That won't work because you have a mysqli_stmt object, and mysqli_fetch_assoc expects a mysqli_result object. This gets a bit tricky because you might not have the MySQL Native Driver installed (that's a server config). If you do, you can fix it like this
$result = mysqli_stmt_get_result($usuarioExiste);
$usuario = mysqli_fetch_assoc($result);
If that function is undefined you'll have to use the much clunkier mysqli_stmt_bind_result and assign variables. The examples here require a lot of recoding on your part, but you can see some examples over at Example of how to use bind_result vs get_result
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);
}
}
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