Problems retrieving result set from SQL server [closed] - php

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";
}
}
?>

Related

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

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)

Parse error: syntax error, unexpected end of file in C:\xampp\htdocs\forgot.php [duplicate]

This question already has answers here:
Parse error: syntax error, unexpected end of file [closed]
(1 answer)
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 6 years ago.
I need your help please, I have tried with several codes, The code is to recover password, but it does not run on xampp
I have a problem with xampp:
Parse error: syntax error, unexpected end of file in C:\xampp\htdocs\forgot.php
Is my code
<?php
if(User == false) {
//Pass
if(isset($_POST['emailAddress'])){
$email = FilterText($_POST['emailAddress']);
$buscar = mysql_query("SELECT mail FROM users WHERE mail = '".$email."'");
$_SESSION['correo'] = $email;
if(mysql_num_rows($buscar) > 0){
$_SESSION['tmptxt_seg'] = GenerateCode();
$code = $_SESSION['tmptxt_seg'];
mail($email,'Recuperación de contraseña - iZabbo', "Estimado usuario, hemos detectado la solicitud del cambio de tu contraseña correctamente. Si no es así ignora este mensaje, de lo contrario haz clic <a href='http://izabbo.com/account/password/resetIdentity/9346b03cbb86c009501ce113cb38dce39ebba9c34a6416d8edef5ac544db7dddb5158bf4e86bc09c089a3ed7e87049f144888ef2b45e1a02986bdc8858d82ad0dd460/?c=".$code."'>Aquí</a> o copia el siguiente enlace:<br> http://izabbo.com/account/password/resetIdentity/9346b03cbb86c009501ce113cb38dce39ebba9c34a6416d8edef5ac544db7dddb5158bf4e86bc09c089a3ed7e87049f144888ef2b45e1a02986bdc8858d82ad0dd460/?c=".$code." <br> ¿No ha funcionado? ¡Manda nuevamente el formulario!", 'soporte#izabbo.com');
echo '<script language="javascript">alert("Te hemos enviado un Email con un enlace para cambiar tu contraseña. Recuerda comprobar también la carpeta de Spam");</script>';
echo '<meta http-equiv="refresh" content="0;url=/index.php">';
}else{
echo '<script language="javascript">alert("El Email ingresado no se encuentra. Intenta registrandote.");</script>';
}
}
//End Pass
$getid = FilterText($_GET['c']);
$correo = $_SESSION['correo'];
if(empty($getid)){
echo '<meta http-equiv="refresh" content="0;url=/index.php">';
}elseif($getid !== $_SESSION['tmptxt_seg']){
echo '<meta http-equiv="refresh" content="0;url=/index.php">';
}
//NEWPASS
if(isset($_POST['newsena'])){
$mail = $_SESSION['correo'];
$contra = FilterText($_POST['newsena']);
$contra2 = FilterText($_POST['newsena2']);
$buscar = mysql_query("SELECT * FROM users WHERE mail = '".$mail."'");
$user = mysql_fetch_array($buscar);
$newpassword = md5($contra);
if(strlen($contra) < 6 || strlen($contra) > 32){
echo '<script language="javascript">alert("Inserta una contraseña válida.");</script>';
header("LOCATION: /account/password/resetIdentity/9346b03cbb86c009501ce113cb38dce39ebba9c34a6416d8edef5ac544db7dddb5158bf4e86bc09c089a3ed7e87049f144888ef2b45e1a02986bdc8858d82ad0dd460/?c=". $_SESSION['tmptxt_seg']."");
}else{
if($contra !== $contra2){
echo '<script language="javascript">alert("Las contraseñas no coinciden.");</script>';
header("LOCATION: /account/password/resetIdentity/9346b03cbb86c009501ce113cb38dce39ebba9c34a6416d8edef5ac544db7dddb5158bf4e86bc09c089a3ed7e87049f144888ef2b45e1a02986bdc8858d82ad0dd460/?c=". $_SESSION['tmptxt_seg']."");
}else{
mysql_query("UPDATE users SET password = '".$newpassword."' WHERE mail = '".$mail."' LIMIT 1");
$_SESSION['Password'] = $newpassword;
echo '<script language="javascript">alert("Contraseña actualizada con éxito.");</script>';
echo '<meta http-equiv="refresh" content="0;url=/index.php">';
}
}
}
//END NEWPASS
?>
You forgot a curly bracket before the end of the PHP script to close if(User == false) {.
Add one just before the ?> and it will work.

cant show up my image php from a DB

the problem is when it does return the binary file, pls help me
<!DOCTYPE html>
<html>
<head>
<title>Tienda Online</title>
<FORM action="upload_imagen.php" enctype="multipart/form-data" method="POST">
<input type="file" name="imagen"> Buscar imagen
<input type="submit" value="Buscar">
</FORM>
<div id="visualizar">
</div>
<form action="mostrar_imagen.php" method="POST">
<input type="text" name="valor" >
<input type="submit" value="mostrar">
</form>
</html>
upload_imagen.php this file upload an image and does storage in a DB
<?php
// Conexion a la base de datos
require "db_model.php";
class upload extends db_model {
function whatever() {
// Comprobamos si ha ocurrido un error.
if (!isset($_FILES["imagen"]) || $_FILES["imagen"]["error"] > 0) {
echo "Ha ocurrido un error.";
} else {
var_dump($_FILES["imagen"]);
// Verificamos si el tipo de archivo es un tipo de imagen permitido.
// y que el tamaño del archivo no exceda los 16MB
$permitidos = array("image/jpg", "image/jpeg", "image/gif", "image/png");
$limite_kb = 16384;
if (in_array($_FILES['imagen']['type'], $permitidos) && $_FILES['imagen']['size'] <= $limite_kb * 1024) {
// Archivo temporal
$imagen_temporal = $_FILES['imagen']['tmp_name'];
// Tipo de archivo
$tipo = $_FILES['imagen']['type'];
// Leemos el contenido del archivo temporal en binario.
$fp = fopen($imagen_temporal, 'r+b');
$data = fread($fp, filesize($imagen_temporal));
fclose($fp);
//Podríamos utilizar también la siguiente instrucción en lugar de las 3 anteriores.
// $data=file_get_contents($imagen_temporal);
// Escapamos los caracteres para que se puedan almacenar en la base de datos correctamente.
$data = mysql_real_escape_string($data);
// Insertamos en la base de datos.
$this->query ="INSERT INTO imagenes (imagen, tipo_imagen) VALUES ('$data', '$tipo')";
$resultado = $this->execute_query();
if ($resultado) {
echo "El archivo ha sido copiado exitosamente.";
} else {
echo "Ocurrió algun error al copiar el archivo.";
}
} else {
echo "Formato de archivo no permitido o excede el tamaño límite de $limite_kb Kbytes.";
}
}
}
}
$obj = new upload();
$obj->whatever();
?>
mostrar_imagen.php this section retrives the image in binary format, then i want to show it, so i read that i need a header and send it the type of image it is for example .jpg, .gif but i dont know if a i have an error
<?php
require 'db_model.php';
class mostrar extends db_model {
function __construct()
{
$id = $_POST['valor'];
$this->query = "SELECT imagen, tipo_imagen
FROM imagenes
WHERE imagen_id=$id";
$datos = $this->execute_query_as();
$imagen = $datos['imagen']; // Datos binarios de la imagen.
$tipo = $datos['tipo_imagen']; // Mime Type de la imagen.
// Mandamos las cabeceras al navegador indicando el tipo de datos que vamos a enviar.
---- > my problem is here, i guess
header("Content-type: image/jpg");
echo $imagen;
// A continuación enviamos el contenido binario de la imagen.
}
}
$obj = new mostrar();
?>
db_model.php
<?php
/**
* clase de la base de datos
*/
include_once('config.php');
class db_model
{
private $db_host = "localhost";
private $db_user = "root";
private $db_pass = "";
protected $db_name = "tienda_cartas";
protected $query;
protected $rows = array();
private $conection;
private function open_conection()
{
$this->conection = new mysqli($this->db_host,$this->db_user,$this->db_pass,$this->db_name);
if ($this->conection->connect_errno) {
echo "error al conectar";
die();
} else {
echo "conectado";
}
}
private function close_conection() {
$this->conection->close();
}
protected function execute_query() {
$this->open_conection();
$result = $this->conection->query($this->query);
if(!$result){
echo "no se pudo ejecutar el sql";
}
$this->close_conection();
return $result;
header("location:index.php");
}
protected function execute_query_as() {
$this->open_conection();
$result = $this->conection->query($this->query);
if(!$result){
echo "no se pudo ejecutar el sql";
}
$array_as = $result->fetch_assoc();
if(!$array_as){
echo "no hay incidencias";
die();
}
$this->close_conection();
return $array_as;
}
}
?>
This could be your problem:
$data = mysql_real_escape_string($data);
In your classes you use mysqli_* functions, but this one belongs to the deprecated mysql_* functions. When you call it it will automatically try to open a new database connection with mysql_connect(), which will fail because it doesn't have any information about your host. mysql_real_escape_string() will then return false:
Warning: mysql_real_escape_string(): A link to the server could not be established in test.php on line 2
bool(false)
Just remove the line, escaping binary data will most probably ruin it anyway. Instead you should use prepared statements to prevent SQL injections.

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

Categories