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().
Related
In a login page in PHP I've to verify if the user has already made a login today but it seems I can't select the max datalogin
<?php
SESSION_START();
$database="***";
$nomeserver="***";
$password="***";
$username="***";
$connessione= mysqli_connect($nomeserver, $username, $password);
//stringa di connessione
if (!$connessione)
die ('<script type="text/javascript">alert("Problemi di connessione al server")</script>');
mysqli_set_charset($connessione,'utf8');
if (! mysqli_select_db($connessione,$database))
die ('<script type="text/javascript">alert("Database non raggiungibile")</script>');
if (!empty($_POST)){
$user=$_POST["user"];
$pass=$_POST["psw"];
//seleziono livello, id e nome solo se nome e password appartengono allo stesso record
$sql= "select id_utente, nome_utente from ut_sec where nome_utente= '$user' and password= '$pass'";
$risultato= mysqli_query($connessione,$sql);
$rows = mysqli_num_rows ($risultato );
$array=mysqli_fetch_array($risultato,MYSQLI_ASSOC);
if (!$risultato)
die ('<script type="text/javascript">alert("Errore 01 nella esecuzione della query")</script>');
else
{
$idut=$array["id_utente"];
$sql= "select MAX(datalogin) from log_sec where idutente= $idut";
$risultato= mysqli_query($connessione,$sql);
$riga= mysqli_fetch_array($risultato,MYSQLI_ASSOC);
if (!$risultato)
die ('<script type="text/javascript">alert("Errore 02 nella esecuzione della query")</script>');
$ultimo=$riga["datalogin"];
date_default_timezone_set('Europe/Rome');
$attuale= date("Y-m-d");
if($ultimo==$attuale)
die("Gia fatto il login");
}
}
?>
The table 'log_sec' is:
log_sec scheme
UPDATE: I've posted all the code of the php script
(Sorry for my English, I'm italian)
I believe there are some errors with your if and else statements. Try this:
//seleziono livello, id e nome solo se nome e password appartengono allo stesso record
$sql= "select id_utente, nome_utente from ut_sec where nome_utente= '$user' and password= '$pass'";
$risultato= mysqli_query($connessione,$sql);
$rows = mysqli_num_rows ($risultato );
$array=mysqli_fetch_array($risultato,MYSQLI_ASSOC);
if (!$risultato) {
die ('<script type="text/javascript">alert("Errore 01 nella esecuzione della query")</script>');
}else{
$idut=$array["id_utente"];
$sql= "select MAX(datalogin) from log_sec where idutente= $idut";
$risultato= mysqli_query($connessione,$sql);
$riga= mysqli_fetch_array($risultato,MYSQLI_ASSOC);
}
if (!$risultato){
die ('<script type="text/javascript">alert("Errore 02 nella esecuzione della query")</script>');
}
$ultimo=$riga["datalogin"];
date_default_timezone_set('Europe/Rome');
$attuale= date("Y-m-d");
if($ultimo==$attuale){
die("Gia fatto il login");
}
I'm new with PHP and SQL...
I'm trying to create new tables based on the url, but it's only working the first time I use it. After that, it's not possible.
Here is my PHP code:
if(isset($_GET['id'])){
$tabela = $_GET['tabela'];
$_GET['id'];
$criar = $tabela . $nivel . $page_id;
// Se clicar no botão 'confirmar', então ele faz o seguinte:
if(isset($_POST['submit'])){
$titulo = $_POST['titulo'];
$_FILES['imagem']['tmp_name'];
$texto = $_POST['texto'];
// Se um destes campos estiver vazio:
if($titulo=='' or $imagem=='' or $texto==''){
echo "Preencha todos os campos para o menu!";
exit(); }
// Se não houver campos vazios, ele faz: else {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "site";
// Ligação à base de dados:
$conn = new mysqli($servername, $username, $password, $dbname);
// Verifica a ligação:
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Cria a nova tabela:
$sql = "CREATE TABLE IF NOT EXISTS $criar (
id INT(9) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
titulo VARCHAR(255),
imagem LONGBLOB,
texto TEXT,
grupo INT(9),
FOREIGN KEY (grupo) REFERENCES $tabela(id)
)";
// Se conseguir ligar-se à base de dados e criar uma nova tabela, ele insere os dados na nova tabela:
if ($conn->query($sql) === TRUE) {
include("includes/connect.php");
mysql_query("SET NAMES 'utf8'");
move_uploaded_file($image_tmp,"../imagens/$imagem");
$insert_query = "INSERT INTO $criar (titulo, imagem, texto, grupo) VALUES ('$titulo','$imagem','$texto','$page_id')";
// Se inserir os dados na nova tabela, ele dá uma mensagem de sucesso:
if(mysql_query($insert_query)){
echo "<script>alert('Menu inserido com sucesso!')</script>";
echo "<script>window.open('index.php','_self')</script>";
}
else{
echo "Erro: " . $insert_query . "<br>" . $conn->error;
}
}
// Caso ele não consiga criar uma nova tabela (porque já existe), ele insere os dados na tabela já existente:
else {
include("includes/connect.php");
mysql_query("SET NAMES 'utf8'");
// Cria a nova tabela:
$sql = "CREATE TABLE IF NOT EXISTS $criar (
id INT(9) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
titulo VARCHAR(255),
imagem LONGBLOB,
texto TEXT,
grupo INT(9),
FOREIGN KEY (grupo) REFERENCES $tabela(id)
)";
if(mysql_query($sql)){
echo "sim!";
}
else {
echo "não!";
}
move_uploaded_file($image_tmp,"../imagens/$imagem");
$insert_query = "INSERT INTO $criar (titulo, imagem, texto, grupo) VALUES ('$titulo','$imagem','$texto','$page_id')";
// Caso consiga inserir os dados na tabela já existente, dá uma mensagem de sucesso:
if(mysql_query($insert_query&&$sql)){
echo "<script>alert('Menu inserido com sucesso!')</script>";
echo "<script>window.open('index.php','_self')</script>";
}
else{
echo "isto não está a correr bem!";
}
// Fecha a ligação à base de dados:
$conn->close();
} } }$nivel = $_GET['grupo']; $page_id =$imagem = $_FILES['imagem']['name']; $image_tmp =
What do you mean 1st time, 2nd time? Do you try to create another table with the same name you just have created? You'll get a table already exists error.
CREATE TABLE IF NOT EXISTS $criar
This explicitly tells MySql not to create the table if it exists, so if you pass the same query parameters to your php then it'll not be able to create the same table again.
Probably you could change it to:
$page_id = $_GET['id'];
$criar = $tabela . $nivel . $page_id;
And then pass a different id and/or different tabela every time.
this code looks behind the issue to me :
$tabela = $_GET['tabela'];
$_GET['id']; //this line looks odd
$criar = $tabela . $nivel . $page_id;
and maybe it's not creating new tables because you give the same $criar every time.
After hours of trying to solve this issue, i finally got good news! :) i was working in my local server (via xampp) and decided to put it online to check if something changes... and dont know why, but it works perfectly online and dont work with xampp! What a mess!! but its working!! thanks all for your help!! ;)
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.
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
I have an webpage on which i want to display 2 separate tables with content from the same database. How do i run separate functions on a webpage and display 2 different results?
The code i have so far:
the second query that i want to run is in it as query2, but this doesn`t work....
<?php
$server = "localhost";
$user = "776";
$wachtwoord = "776";
$database = "kse001_h5mh";
$query = "SELECT beschrijving FROM supermarkt WHERE soort = 'komkommertest'"; //de SQL-query
$resultaat = ""; // hierin wordt het resultaat van de query opgeslagen
if (!$db = mysql_connect($server, $user, $wachtwoord)){ // probeert de verbinding te maken
$melding = "<h2>Verbinding maken met databaseserver is mislukt!</h2>";
}
else{
$melding = "<h2>Verbinding maken met databaseserver is tot stand gebracht!</h2>";
if(!mysql_select_db($database)){ // open de gewenste database
$melding .= "...maar de database \"$database\" kon niet worden gevonden!";
} else {
$melding .= "en de database \"$database\" is geselecteerd!";
if(!$resultaat = mysql_query($query, $db)){
$melding .= "<br />...maar de query \"$query\" kon niet worden uitgevoerd!";
} else {
$melding .="<br />De query \"$query\" is met succes uitgevoerd!";
}
}
$query2 = "SELECT beschrijving FROM supermarkt WHERE soort = 'hamburger'"; //de SQL-query
$resultaat2 = ""; // hierin wordt het resultaat van de query opgeslagen
if (!$db = mysql_connect($server, $user, $wachtwoord)){ // probeert de verbinding te maken
$melding = "<h2>Verbinding maken met databaseserver is mislukt!</h2>";
} else {
$melding = "<h2>Verbinding maken met databaseserver is tot stand gebracht!</h2>";
if(!mysql_select_db($database)){ // open de gewenste database
$melding .= "...maar de database \"$database\" kon niet worden gevonden!";
} else {
$melding .= "en de database \"$database\" is geselecteerd!";
if(!$resultaat2 = mysql_query($query, $db)){
$melding .= "<br />...maar de query \"$query\" kon niet worden uitgevoerd!";
} else {
$melding .="<br />De query \"$query\" is met succes uitgevoerd!";
}
}
mysql_close($db); //database afsluiten
?>
</head>
<body>
<?php echo $melding; ?>
<hr />
<?php
while(list($bescrijving) = mysql_fetch_row($resultaat))
{
echo "$bescrijving is geboren op <br />";
}
?>
<?php
while(list($bescrijving) = mysql_fetch_row($resultaat2))
{
echo "$bescrijving is geboren op <br />";
}
?>
</body>
First problem, stop using mysql_ functions family... this kind of function was deprecated and will stop work soon or just don't run appropriately.
You should change to PDO family functions try this:
$dbh = new PDO('mysql:host=localhost;dbname=kse001_h5mh', '776', '776');
$query1 = $dbh->query("SELECT beschrijving FROM supermarkt WHERE soort = 'komkommertest'");
$query1->fetchAll(); // bring the result
$query2 = $dbh->query("SELECT beschrijving FROM supermarkt WHERE soort = 'hamburger'");
$query2->fetchAll(); // bring the result
This should work.
You can run 2 process of your script using the pcntl-fork function.
You can also try to use ob_flush function to send the output buffer between your 2 database requests.
In your case, I think it's a better option to load data in AJAX if it's possible.