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
Related
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.
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
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Hello all I am doing a form in php since drupal in which I have a text box and a push button, the input of a code (varchar) and this is compared to a record in sqlserver at the time of performing the validation Code entered In the form exists in the DB) executes an iframe with a stored procedure.
This is the code, I think I'm doing something wrong with the php code and select it because the moment of entering the value to query does not generate the text "all right" or the "number consulted does not exist" found in He does
I thank those who tell me to help and guide
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Buscador php</title>
<form method="POST" action="" onSubmit="return validarForm(this)">
<input type="text" placeholder="Buscar usuario" name="palabra">
<input type="submit" value="Buscar" name="buscar">
</form>
</meta>
<script type="text/javascript">
function validarForm(formulario)
{
if(formulario.palabra.value.length==0)
{ //¿Tiene 0 caracteres?
formulario.palabra.focus(); // Damos el foco al control
alert('Debes rellenar este campo'); //Mostramos el mensaje
return false;
} //devolvemos el foco
return true; //Si ha llegado hasta aquí, es que todo es correcto
}
</script>
</html>
</head>
<?php
//si existe una petición
if($_POST['buscar'])
{
$usuario= '';
$pass = '';
$servidor = '';
$basedatos = '';
$info = array('Database'=>$basedatos, 'UID'=>$usuario, 'PWD'=>$pass);
$conexion = sqlsrv_connect($servidor, $info);
if(!$conexion){
die( print_r( sqlsrv_errors(), true));
}
echo 'Conectado';
$buscar = $_POST["palabra"];
$arrojado = sqlsrv_query("SELECT ID from Venta
where ID like '%buscar%'",$conexion) or
die("Problemas en el select:".sqlsrv_error());
?>
//$resultado = sqlsrv_fetch_array($arrojado);
<?php
$valor = $resultado['aleatoria']; //LE ASIGNAMOS UNA VARIABLE AL RESULTADO DE LA CONSULTA
//COMPARAMOS CON UNA CONDICIONAL
if($arrojado == $buscar){
echo"todo bien";
}
else {
echo "El numero consultado no existe";
?>
First you should read the answers to this question: How to get useful error messages in PHP? It would have saved you a lot of trouble.
You are trying to compare a database result to a string, which will not work:
$buscar = $_POST["palabra"];
...
$arrojado = sqlsrv_query("...");
...
if($arrojado == $buscar) {
...
}
You're also passing parameters to sqlsrv_query() in the wrong order, and were missing 2 closing braces at the end of your code and a space after an echo statement.
You need to fetch the row from the result set, and then get the first entry from it:
<?php
if($_POST['buscar']) {
$usuario= '';
$pass = '';
$servidor = '';
$basedatos = '';
$info = array('Database'=>$basedatos, 'UID'=>$usuario, 'PWD'=>$pass);
$conexion = sqlsrv_connect($servidor, $info);
if(!$conexion){
die( print_r( sqlsrv_errors(), true));
}
echo 'Conectado';
$buscar = $_POST["palabra"];
$arrojado = sqlsrv_query($conexion, "SELECT `ID` FROM Venta WHERE `ID` LIKE '%buscar%'");
if (!$arrojado) {
die("Problemas en el select:".sqlsrv_error());
}
$row = sqlsrv_fetch_array($arrojado, SQLSRV_FETCH_ASSOC);
//COMPARAMOS CON UNA CONDICIONAL
if($arrojado["ID"] == $buscar){
echo "todo bien";
} else {
echo "El numero consultado no existe";
}
}
?>
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;
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().