I can't delete fields in a mysql database - php

I need to delete to generate a form to select in checkboxes which users I want to delete from the database. To search the users and generate the form I use this code:
<?php
$con = new mysqli('localhost', 'root', '', 'prueba');
$busqueda ="";
$busqueda=$_POST['busqueda'] ;
// funcion para convertir el contenido de un array en un string
function makestring($array)
{
$outval = '';
if (is_array($array)) {
foreach($array as $key=>$value)
{
if(is_array($value))
{
$outval = makestring($value);
}
else
{
$outval = $value;
}
}
}
return $outval;
}
if ($busqueda!=""){
$busca = mysqli_query($con, " SELECT usuario FROM usuarios WHERE
usuario LIKE '%$busqueda%'");
echo "<form action='borrar.php' method='post' enctype='multipart/form-data'>";
while ($array= mysqli_fetch_array($busca)){
$user=makestring($array);
echo"Usuario: <input type='checkbox' name='borrar_usuario[]' value='$user' />$user<br/>";
}
echo " <input type='submit' name='boton' value='eliminar' />";
echo "</form>";
}
$all =$_POST['todos'] ;
if ($all=='borrar_todos'){
$busca = mysqli_query($con, "select usuario from usuarios ");
echo "<form action='borrar.php' method='post' enctype='multipart/form-data'>";
while ($f = mysqli_fetch_array($busca)){
$user=makestring($f);
echo "Usuario: <input type='checkbox' name='borrar_usuario[]' value='$user' />$user<br/>";
}
echo " <input type='submit' name='boton' value='eliminar' />";
echo "</form>";
}
?>
I use this code to collect the data from the forms with this code:
<?php
$con = new mysqli('localhost', 'root', '', 'prueba');
if(isset($_REQUEST["borrar_usuario"])) {
$del_user = $_POST["borrar_usuario"];
$mensaje = "¿Está seguro que quiere eliminar el usuario <b>$row[usuarioNombre]</b>?";
}
// mostramos el mensage
echo $mensaje;
mysqli_query($con, "delete usuario, password, descripcion from usuarios
where usuario in like '$del_user'");
echo "usuario borrado";
header('refresh: 3; url= exito.php');
?>
But it doesn't delete anything in the database. Any help please?

DELETE deletes the entire row from the database. You question feels like you need to Empty some specific fields. Try the following Code
mysqli_query($con, "UPDATE usuarios SET usuario = null, password =null,
descripcion=null where usuario like '$del_user'");

If you want to empty a field or fields, you need to use update usuarios set usuario = '', password = '', descripcion = '' where usuario like '$del_user'"

Try this as the delete query
"delete from usuarios where usuario = '$del_user'"

Use this if you delete one user at the time:
delete from usuarios where usuario = '$del_user'
or this if you delete more users and have ids in comma(,) delimited list
delete from usuarios where usuario in ('$del_user')

Related

Truncated incorrect DOUBLE value: | Error when trying to update data in database

I'm trying to make a poll where the user is voting through a PHP page sending data to a database where I store the values of the poll results.
I'm also trying to make it not possible to vote with the same account more than once. In this area, I've hit a roadblock. When I take the ID which in the code is $userid which is collected from a query and then passed to the vote.php in a $_SESSION it says that
Truncated incorrect DOUBLE value: 3.
It's calling my variable DOUBLE value?
Code of Login.php :
$sqlID = "SELECT ID FROM Users WHERE Konto = '$user'";
$checkID = $connection->query($sqlID);
while ($row = $checkID->fetch_assoc()) {
$setID = $row['ID']."<br>";
}
$_SESSION['sess_id'] = $setID;
$_SESSION['inloggning'] = TRUE; // Ger inloggning en boolean som används senare.
Code of Vote.php :
$userid = $_SESSION['sess_id'];
$voteValidate = "SELECT has_voted FROM Users WHERE ID = '$userid'";
$voteValidationResult = $connection->query($voteValidate);
while ($row = $voteValidationResult->fetch_assoc()) {
$checkVoted = $row['has_voted']."<br>";
}
if ($_SESSION['inloggning'] != TRUE || $checkVoted != 0) { // Tar variabler från login.php och kontrollerar dem, om de inte är sanna så skickas man tillbaka.
echo "<script type='text/javascript'>alert('Du är antingen inte inloggad eller så har du redan röstat.');</script>";
// header("Location: skyddad_sida.php"); // Skickar tillbaka en användare om de har kommit till skyddad_sida.php utan att gå igenom login.php.
exit;
}
if (isset($_POST["voteOriginal"])) {
$voteQuery = "UPDATE polls_choices SET poll_vote_amount = poll_vote_amount + 1 WHERE poll_choice_name = 'Original'";
$voteExecute = $connection->query($voteQuery); // Utför förfrågan i databas.
$preventVote = "UPDATE users SET has_voted = 1 WHERE ID = '$userid'";
if ($connection->query($preventVote) === TRUE) { // Queryar databasen och kontrollerar att det fungerade.
echo "<strong><font color ='green'>Bra.</font></strong>";
} else { // Annars blir det en error.
echo "Error: " . $preventVote . "<br>" . $connection->error . "$userid";
}

A php code able to exec all SQL code

I'm making an intranet.
Only admin have access to the page i want to build now :
I have a page with a textarea. When they click on the send button, it comming to a PHP page to send a req like "UPDATE ... " or "SELECT ...".
He can write the SQL request he want. It's supposed to works.
I want it to work : If it's an update i need to return he if it's ok, if its a select i need to return a table.
But i need it to be able to exec complex request like :
SELECT numfou,
(SELECT COUNT(*)
FROM PROPOSER P
WHERE P.numfou = F.numfou) AS NB_PROD
FROM FOURNISSEUR F;
(net exemple).<br/>
Do you know a PHP code to exec any SQL req?
I suggest this code i make (If you think it can be update say it :D) :
<?php
function requette($req){
$premierMot = explode(" ", $req)[0];
switch(strtoupper($premierMot)){
case "SELECT":
return select($req);
break;
case "UPDATE":
case "DELETE":
case "INSERT":
return updateDeleteInsert($req);
break;
}
}
function select($req){
$bdd = new PDO('mysql:host=localhost;dbname=spb', 'root', '');
// ON DETERMINE SI LE CLIENT RECHERCHE DANS CHAMPS EN PARTICULIER OU TOUT
$explosion = preg_split('/[;, \n]+/', $req);
$veuxTout = false;
for($cpt=0;$cpt<count($explosion);$cpt++){
if(strtoupper($explosion[$cpt]) == "*"){
$veuxTout = true;
break;
}
}
// SI IL NE VEUX PAS TOUT ON PREVOI UN TABLEAU DE DEMANDE
$demande = array();
for($cpt=1;$cpt<count($explosion);$cpt++){
if(strtoupper($explosion[$cpt]) == "FROM"){
break;
}
else{
array_push($demande,$explosion[$cpt]);
}
}
// ON CHERCHE LE NOM DE LA TABLE
$table = "";
for($cpt=0;$cpt<count($explosion);$cpt++){
if(strtoupper($explosion[$cpt]) == "FROM"){
$table = $explosion[$cpt+1];
break;
}
}
// ON CHERCHE LES TITRES DE LA TABLE
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='$table';";
$res = $bdd->query($sql);
$titres = array();
while($resultat = $res->fetch()){
array_push($titres,$resultat['COLUMN_NAME']);
}
$res = $bdd->query($req);
$table = "<table>";
while($resultat = $res->fetch()){
$table .= "<tr>";
if($veuxTout == true){
for($cpt=0;$cpt<count($titres);$cpt++){
$table .= "<td>".$resultat[$titres[$cpt]]."</td>";
}
}
else{
$ok = false;
for($cpt1=0;$cpt1<count($titres);$cpt1++){
for($cpt2=0;$cpt2<count($demande);$cpt2++){
if(strtoupper($titres[$cpt1]) == strtoupper($demande[$cpt2])){
$table .= "<td>".$resultat[$titres[$cpt1]]."</td>";
$ok = true;
}
}
}
}
$table .= "</tr>";
}
$table .= "</table>";
return $table;
}
function updateDeleteInsert($req){
$bdd = new PDO('mysql:host=localhost;dbname=spb', 'root', '');
try {
$req = $bdd->prepare($req);
$req->execute();
return "oui";
}
catch(PDOException $e){
return "non";
}
}
$req = htmlentities($_POST['req']);
echo requette($req);
?>

Delete images from two directories

I have a script that loads images in the database and in two directories: uploads / original and a directory for the preview: uploads / thumbs
I need to create a small panel to delete inserted images, I have already created the code to delete from the database, but I can not delete them from the two directories.
I know I need to use unlink, but I'm no expert, I do not know where to place the code etc. I ask for help to you.
This is the file that I delete.php structured so far:
<?php
$con = mysql_connect("localhost","*******","******");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("**********************", $con);
if($_POST)
{
$ids = isset($_POST['id']) ? $_POST['id'] : array();
elimina_record($ids);
}
elseif(isset($_GET['id']))
{
elimina_record(array($_GET['id']));
}
else
mostra_lista();
function mostra_lista()
{
// mostro un eventuale messaggio
if(isset($_GET['msg']))
echo '<b>'.htmlentities($_GET['msg']).'</b><br /><br />';
// preparo la query
$query = "SELECT id,name,filename FROM image";
// invio la query
$result = mysql_query($query);
// controllo l'esito
if (!$result) {
die("Errore nella query $query: " . mysql_error());
}
echo '
<form name="form1" method="post" action="">
<table border="1">
<tr>
<th> </th>
<th>ID</th>
<th> </th>
</tr>';
while ($row = mysql_fetch_assoc($result))
{
$name = htmlentities($row['name']);
$id = htmlentities($row['id']);
$filename = htmlentities($row['filename']);
// preparo il link per la modifica dei dati del record
$link = $_SERVER['PHP_SELF'].'?id=' . $row['id'];
echo "<tr>
<td><input name=\"id[]\" type=\"checkbox\" value=\"$row[id]\" /></td>
<td>$id</td>
<td>delete</td>
</tr>";
}
echo '</table>
<br />
<input type="submit" name="Submit" value="Elimina record selezionati" />
</form>';
// libero la memoria di PHP occupata dai record estratti con la SELECT
mysql_free_result($result);
// chiudo la connessione a MySQL
mysql_close();
}
function elimina_record($ids)
{
// verifico che almeno un id sia stato selezionato
if(count($ids) < 1)
{
$messaggio = urlencode("Nessun record selezionato!");
header('location: '.$_SERVER['PHP_SELF'].'?msg='.$messaggio);
exit;
}
// per precauzione converto gli ID in interi
$ids = array_map('intval',$ids);
// creo una lista di ID per la query
$ids = implode(',',$ids);
// preparo la query
$query = "DELETE FROM image WHERE id IN ($ids)";
// invio la query
$result = mysql_query($query);
// controllo l'esito
if (!$result) {
die("Errore nella query $query: " . mysql_error());
}
// conto il numero di record cancellati
$num_record = mysql_affected_rows();
// chiudo la connessione a MySQL
mysql_close();
$messaggio = urlencode("Numero record cancellati: $num_record");
header('location: '.$_SERVER['PHP_SELF'].'?msg='.$messaggio);
}
?>
While, it may be useful, even paste the file to upload.php files:
session_start();
$_SESSION['id']="1";
$id=$_SESSION['id'];
include 'config.php'; //assume you have connected to database already.
$folder = 'uploads/';
$name = date('YmdHis');
$filename = md5($_SERVER['REMOTE_ADDR'].rand()).'.jpg';
$original = $folder.$filename;
// The JPEG snapshot is sent as raw input:
$input = file_get_contents('php://input');
if(md5($input) == '7d4df9cc423720b7f1f3d672b89362be'){
// Blank image. We don't need this one.
exit;
}
$result = file_put_contents($original, $input);
if (!$result) {
echo '{
"error" : 1,
"message" : "Failed save the image. Make sure you chmod the uploads folder and its subfolders to 777."
}';
exit;
}
$info = getimagesize($original);
if($info['mime'] != 'image/jpeg'){
unlink($original);
exit;
}
// Moving the temporary file to the originals folder:
rename($original,'uploads/original/'.$filename);
$original = 'uploads/original/'.$filename;
// Using the GD library to resize
// the image into a thumbnail:
$origImage = imagecreatefromjpeg($original);
$newImage = imagecreatetruecolor(154,110);
imagecopyresampled($newImage,$origImage,0,0,0,0,154,110,520,370);
imagejpeg($newImage,'uploads/thumbs/'.$filename);
echo '{"status":1,"message":"Success!","filename":"'.$filename.'"}';
$sql="INSERT INTO image VALUES ('','$name','$filename')";
$result=mysqli_query($con,$sql);
$value=mysqli_insert_id($con);
$_SESSION["myvalue"]=$value;
$cart_1="/uploads/original/";
$cart_2="/uploads/thumbs/";
foreach($files as $file){
$f_1=$cart_1.$file;
$f_2=$cart_2.$file;
unlink($f_1);
unlink($f_2);
}
Check this out:
$dir1 = '/upload/original/';
$dir2 = '/upload/thumbs/';
$image = 'abc.jpg';
if(file_exists($dir1.$image))
unlink($dir1.$image);
if(file_exists($dir2.$image))
unlink($dir2.$image);

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().

Why is mysql_num_rows() returning 0?

I have read in another threads that pasting the query in phpMyAdmin returns the amount of rows that you have, but in my case it doesn't even returns a value in phpMyAdmin, it's always 0! Here is the query:
$query = "SELECT nom_usu FROM usuarios WHERE nom_usu = '$usu' AND pass = '$pass';";
I open the .php file and run the query and it returns empty values, like this:
SELECT nom_usu FROM usuarios WHERE nom_usu = '' AND pass = '';
I also tried to echo the value that returns and is, guess what? Zero!
Here is the complete .php file (is for a login):
<?php
include('dbConfig.php');
$usu = $_POST["usu"];
$pass = $_POST["pass"];
$query = "SELECT nom_usu FROM usuarios WHERE nom_usu = '$usu' AND pass = '$pass';";
echo $query."\n";
if($resultado = mysql_query($query)){
if(mysql_num_rows($resultado) > 0){
echo mysql_num_rows($resultado);
echo "Todo está bien, no te preocupes :)";
echo true;
} else {
echo mysql_num_rows($resultado);
echo "Hay algo mal aquí :(";
}
} else {
echo false;
}
?>
And the dbConfig.php file:
<?php
$host="localhost";
$user="neosoftw_lambda";
$contra="myPass"; <- This is not actually my password...
$db="neosoftw_lambdaMovil";
$ms = mysql_connect($host, $user, $contra) or die("No se pudo conectar :(");
mysql_select_db($db, $ms) or die ("No hay base de datos :(");
?>
Hope someone can help me figure out where I have gone wrong?
Here is what I want to make, is a login in jQuery Mobile, but it doesn't work!
Username: bryan
Password: azul
http://android.neosoftware.org.mx/
Edit
Maybe it could be because of my javascript?
$.post("http://android.neosoftware.org.mx/PHP/login.php", {usu : usu, pass : pass}, function(respuesta_login){
if(!($("#txt_usuario").val() || $("#txt_password") == '')){
$.mobile.changePage("#campos_vacios");
} else {
if(respuesta_login == 1){
$("#txt_usuario").val('');
$("#txt_password").val('');
$.mobile.changePage("#pag_principal");
} else {
$.mobile.changePage("#error_login");
}
}
});
Use mysqli or PDO statements, as mysql is deprecated. Try this:
$usu = mysqli_real_escape_string($_POST["usu"]);
$pass = mysqli_real_escape_string($_POST["pass"]);
$query = "SELECT nom_usu FROM usuarios WHERE nom_usu = '".$usu."' AND pass = '".$pass."'";
And also your condition is incorrect.It should be like this:
if($resultado == mysqli_query($query)){
Try this query.
$query = "SELECT `nom_usu` FROM usuarios WHERE `nom_usu` = '".$usu."' AND `pass` = '".$pass."'";
Also this type of problem occurre when $_POST variable is empty.. So, double check your code.
Note : mysql_* function is deprecated, move on mysqli_* function asap.

Categories