How delete a row with php in mysql? - php

I have this code and i'm doing a dropdown to people choose what notice they want to delete, but i don't know what is wrong in my code......i'm new..so sorry for my ignorance
PHP code:
<?php
include('configdb.php')
if(isset($_POST['delete']))
{
$query_delete = "DELETE from artigos where idartigos >0";
$resultado_delete = mysqli_query($mysqli,$query_delete) or
die(mysqli_error($mysqli));
if($resultado_delete)
{
echo "
<script language='JavaScript'>
window.alert('Notícia eliminada com sucesso. Clique para voltar à página inicial.')
window.location.href='index.php';
</script>";
}
else
{
echo "
<script language='JavaScript'>
window.alert('Não foi possível apagar a sua notícia. Tente novamente, sff. Clique para voltar à página inicial.')
window.location.href='index.php';
</script>";
}
}
?>
HTML CODE:
<h1>Apagar notícia</h1>
<a>Notícias disponíveis</a><br><br>
<select name="delete" style="width:332px">
<?php echo $artigos; ?>
</select><br><br>
<p>eliminar
<input type="submit" name="submit" id="submit" action= "delete.php" value="delete" />
</p>
This is how it looks:

<form action="delete.php">
<select name="delete">
<option value=" ">blank</option>
<option value=" <?php echo $artigos; ?> "> <?php echo $artigos; ?> </option>
</select>
<input type="submit" value="Submit">
</form>

Related

Request Dropdown list

I have a dropdown list with 5 elements (Volleyball, Handball, Rugby, Basketball, Autres)
I wish for example to select the element "Rugby" in my form, then confirm.
My problem is when I wish to change my old choice in my form (edit); the element "Rugby" is not the element which has been save previously.
By default I always have the element "VolleyBall".
[![<td>Type de Club:</td><td>
<select name="type_club" style="width:144px">
<option>Volley-Ball</option>
<option>Hand-Ball</option>
<option>Rugby</option>
<option>Basket-Ball</option>
<option>Autres</option>
</select>][1]][1]
[1]: https://i.stack.imgur.com/xQ83B.png
Here is my code.
<?php
// including the database connection file
include_once("config_bd.php");
if(isset($_POST['update']))
{
$pk_club = mysqli_real_escape_string($mysqli, $_POST['pk_club']);
$nom_club = mysqli_real_escape_string($mysqli, $_POST['nom_club']);
$type_club = mysqli_real_escape_string($mysqli, $_POST['type_club']);
// checking empty fields
if(empty($nom_club) || empty($type_club)) {
if(empty($nom_club)) {
echo "<font color='red'>Le nom du club est vide.</font><br/>";
}
if(empty($type_club)) {
echo "<font color='red'>Le type du club est vide.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($mysqli, "UPDATE clubs SET nom_club='$nom_club',type_club='$type_club' WHERE pk_club=$pk_club");
//redirectig to the display page. In our case, it is index.php
header("Location: vue_club.php");
}
}
//getting id from url
$pk_club = $_GET['pk_club'];
//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM clubs WHERE pk_club=$pk_club");
while($res = mysqli_fetch_array($result))
{
$nom_club = $res['nom_club'];
$type_club = $res['type_club'];
}
?>
<html>
<head>
</head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Palais des Sports</title>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="style/style1.css">
<body>
<div class="bandeau-bleu">
<h2>Palais des Sports</h2>
<i class="material-icons"></i>
<i class="material-icons"></i>
</div>
<div class="form_encodage">
<h3>Cliquez ici pour afficher les enregistrements</h3>
<br />
<h4> Editer un enregistrement</h4><br />
<form name="form1" method="post" action="edit_club.php">
<table border="0">
<tr>
<td>Nom du Club:</td>
<td><input type="text" name="nom_club" value="<?php echo $nom_club;?>"></td>
</tr>
<tr>
<td>Type de Club:</td><td>
<select name="type_club" style="width:144px">
<option>Volley-Ball</option>
<option>Hand-Ball</option>
<option>Rugby</option>
<option>Basket-Ball</option>
<option>Autres</option>
</select>
</td></tr>
<td><input type="submit" name="update" class="bouton_bleu" value="Update"></td>
<td><input type="hidden" name="pk_club" value=<?php echo $_GET['pk_club'];?>></td>
</tr>
</table>
</form>
</div>
</body>
</html>
You can use selected property with options.
Below is updated code for dropdown you have put thin td.
Try this:
<td>Type de Club:</td><td>
<select name="type_club" style="width:144px">
<option <?php if(isset($type_club) and $type_club=='Volley-Ball'){ echo 'selected'; }?>>Volley-Ball</option>
<option <?php if(isset($type_club) and $type_club=='Hand-Ball'){ echo 'selected'; }?>>Hand-Ball</option>
<option <?php if(isset($type_club) and $type_club=='Rugby'){ echo 'selected'; }?>>Rugby</option>
<option <?php if(isset($type_club) and $type_club=='Basket-Ball'){ echo 'selected'; }?>>Basket-Ball</option>
<option <?php if(isset($type_club) and $type_club=='Autres'){ echo 'selected'; }?>>Autres</option>
</select>
</td>
Complete updated code:
<?php
// including the database connection file
include_once("config_bd.php");
if(isset($_POST['update']))
{
$pk_club = mysqli_real_escape_string($mysqli, $_POST['pk_club']);
$nom_club = mysqli_real_escape_string($mysqli, $_POST['nom_club']);
$type_club = mysqli_real_escape_string($mysqli, $_POST['type_club']);
// checking empty fields
if(empty($nom_club) || empty($type_club)) {
if(empty($nom_club)) {
echo "<font color='red'>Le nom du club est vide.</font><br/>";
}
if(empty($type_club)) {
echo "<font color='red'>Le type du club est vide.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($mysqli, "UPDATE clubs SET nom_club='$nom_club',type_club='$type_club' WHERE pk_club=$pk_club");
//redirectig to the display page. In our case, it is index.php
header("Location: vue_club.php");
}
}
//getting id from url
$pk_club = $_GET['pk_club'];
//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM clubs WHERE pk_club=$pk_club");
while($res = mysqli_fetch_array($result))
{
$nom_club = $res['nom_club'];
$type_club = $res['type_club'];
}
?>
<html>
<head>
</head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Palais des Sports</title>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="style/style1.css">
<body>
<div class="bandeau-bleu">
<h2>Palais des Sports</h2>
<i class="material-icons"></i>
<i class="material-icons"></i>
</div>
<div class="form_encodage">
<h3>Cliquez ici pour afficher les enregistrements</h3>
<br />
<h4> Editer un enregistrement</h4><br />
<form name="form1" method="post" action="edit_club.php">
<table border="0">
<tr>
<td>Nom du Club:</td>
<td><input type="text" name="nom_club" value="<?php echo $nom_club;?>"></td>
</tr>
<tr>
<td>Type de Club:</td><td>
<select name="type_club" style="width:144px">
<option <?php if(isset($type_club) and $type_club=='Volley-Ball'){ echo 'selected'; } ?>>Volley-Ball</option>
<option <?php if(isset($type_club) and $type_club=='Hand-Ball'){ echo 'selected'; } ?>>Hand-Ball</option>
<option <?php if(isset($type_club) and $type_club=='Rugby'){ echo 'selected'; } ?>>Rugby</option>
<option <?php if(isset($type_club) and $type_club=='Basket-Ball'){ echo 'selected'; } ?>>Basket-Ball</option>
<option <?php if(isset($type_club) and $type_club=='Autres'){ echo 'selected'; }?>>Autres</option>
</select>
</td></tr>
<td><input type="submit" name="update" class="bouton_bleu" value="Update"></td>
<td><input type="hidden" name="pk_club" value=<?php echo $_GET['pk_club'];?>></td>
</tr>
</table>
</form>
</div>
</body>
</html>
You will need to query your database before loading your select form to get the previous save then build your list
$sqla= "SELECT * FROM `save_table` WHERE `id` = $id ";
$result = $conn->query($sqla);
if ($result->num_rows > 0) {
$save = $row['save'];
$select= ('<td>Type de Club:</td><td>
<select name="type_club" style="width:144px">
<option>');
$select.='$save';
$select.='</option> <option>Volley-Ball</option>
<option>Hand-Ball</option>
<option>Rugby</option>
<option>Basket-Ball</option>
<option>Autres</option>
</select>';
echo $select;
You can also use if statements to remove the second $save variable from the list before you build it so there is no repeat option in the list.

Show all records of a MySQL field in a Select HTML

Good day, I am making a system for the university of the reservation of some mini-auditors, One (01) user can make several reservations and after booking the user must inform the payment by uploading a pdf.
To the user I show a form to inform the payment by uploading the pdf with the reservation number and the mini-audit, but if I have several reservations I need to show them all so that he selects which of all the reservations he made paid and wants to inform, as I have the code now only shows me the first reservation and I hope that when I click on the "select" HTML I will display all the reservation numbers that it has together with the mini-audit associated with that reservation. Then I leave the code (I apologize, I'm learning and I probably have many errors, Im sorry for my bad english too):
This is an example that how looks now https://i.imgur.com/XvRdRTe.gif
<?php
session_start();
include '/login/funcs/funcs.php';
include_once 'config.inc.php';
if(!isset($_SESSION["id_usuario"])){ //Si no ha iniciado sesión redirecciona a index.php
header("Location: index.php");
}
$idUsuario = $_SESSION['id_usuario'];
$db=new Conect_MySql();
$sql2 = "SELECT `idsolicitudes`, `id`, `nombre_sala` FROM solicitudes WHERE `id`=$idUsuario";
$query2 = $db->execute($sql2);
$datos=$db->fetch_row($query2);
$sql3 = "SELECT `id`, `usuario`, `nombre`, `apellido` FROM usuarios WHERE `id`=$idUsuario";
$query3 = $db->execute($sql3);
$datos2=$db->fetch_row($query3);
echo $datos['usuario'];
?>
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<?php
if (isset($_POST['subir'])) {
$nombre = $_FILES['archivo']['name'];
$tipo = $_FILES['archivo']['type'];
$tamanio = $_FILES['archivo']['size'];
$ruta = $_FILES['archivo']['tmp_name'];
$destino = "archivos/" . $nombre;
if ($nombre != "") {
if (copy($ruta, $destino)) {
$titulo= $_POST['titulo'];
$descri= $_POST['descripcion'];
$solicitud = $_POST ['solicitud'];
$db=new Conect_MySql();
$sql = "INSERT INTO tbl_documentos(idsolicitud, id, titulo,descripcion,tamanio,tipo,nombre_archivo) VALUES('$solicitud','$idUsuario','$titulo','$descri','$tamanio','$tipo','$nombre')";
$query = $db->execute($sql);
if($query){
echo '<script type="text/javascript">';
echo 'setTimeout(function () { swal("Buen trabajo!","Hemos recibido la información de tu pago, pero primero debemos confirmarla, espera por nuestro correo electrónico con información detallada!","success");';
echo '}, 1000);</script>';
/*
echo "<script type=\"text/javascript\">swal(\"Se guardó correctamente\");
window.location.href='/login/welcome.php';
</script>";*/
}
} else {
echo "Error";
}
}
}
?>
<body>
<div align="center" class="main"> <!-- Primer Div Parallax -->
<div class="container" id="stuff">
<div style="width: 500px; margin: auto; style=background-color:white; padding: 30px;">
<h2 id="stuff" style="background-color:#1c1c1c"><b>Informános tu pago</b></h2>
<h4 ><b>Sube tu comprobante de deposito o transferencia solo despues de haber reservado</b></h4>
<form method="post" action="" enctype="multipart/form-data">
<table>
<div class="form-group">
<tr>
<td><label>Miniauditorio</label></td>
<td><div class="col-sm-10">
<select id="disabledSelect" name="titulo" style="WIDTH: 228px; HEIGHT: 40px" class="form-control" placeholder="<?php echo $datos['nombre_sala']; ?>">
<option placeholder="<?php echo $datos['idsolicitud']; ?>"><?php echo $datos['nombre_sala']; ?></option>
</select>
</div>
</td>
</div>
</tr>
</div>
<tr>
<td><label><br />Nombre Titular</label></td>
<td><br /><input style="WIDTH: 250px; HEIGHT: 35px" class="form-control" style="color:black" name="descripcion" disabled value="<?php echo $datos2['nombre']; ?> <?php echo $datos2['apellido']; ?>"></td>
</tr>
<img class="img2" src="/login/images/pdficon.png">
<tr>
<td><label><br />Número de Solicitud</label></td>
<td><div class="col-sm-10">
<select id="disabledSelect" name="titulo" style="WIDTH: 228px; HEIGHT: 40px" class="form-control" placeholder="<?php echo $datos['nombre_sala']; ?>">
<option placeholder="<?php echo $datos['idsolicitud']; ?>"><?php echo $datos['idsolicitudes']; ?></option>
</select>
</tr>
<td colspan="2"><br />
<span class="btn btn-default btn-file">
<input type="file" name="archivo"></td>
</span>
<div align="center">
<tr align="center">
<td align="center"><br /><input align="center" class="btn btn-success" type="submit" value="Subir" name="subir"></td>
<!-- <td>lista</td> -->
</tr>
</div>
</table>
<h4><b>Antes de enviarnos su información, verifique que su archivo este guardado en formato PDF</b></h2>
</form>
</div>
</div>
<!-- Posible imagen<img src="https://i.imgur.com/5utiwXU.jpg">-->
</body>
</html>
This is my connection functions
<?php
class Conect_MySql {
var $obj = array ( "dbname" => "login",
"dbuser" => "root" ,
"dbpwd" => "" ,
"dbhost" => "localhost" );
var $q_id ="";
var $ExeBit ="";
var $db_connect_id = "";
var $query_count = 0;
private function connect(){
$this->db_connect_id = mysqli_connect($this->obj['dbhost'],$this->obj['dbuser'],$this->obj['dbpwd'],$this->obj['dbname']);
if (!$this->db_connect_id)
{
echo (" Error no se puede conectar al servidor:".mysqli_connect_error());
}
}
function execute($query) {
$this->q_id = mysqli_query($this->db_connect_id,$query);
if(!$this->q_id ) {
$error1 = mysqli_error($this->db_connect_id);
die ("ERROR: error DB.<br> No Se Puede Ejecutar La Consulta:<br> $query <br>MySql Tipo De Error: $error1");
exit;
}
$this->query_count++;
return $this->q_id;
}
public function fetch_row($q_id = "") {
if ($q_id == "") {
$q_id = $this->q_id;
}
$result = mysqli_fetch_array($q_id);
return $result;
}
public function get_num_rows() {
return mysqli_num_rows($this->q_id);
}
public function get_row_affected(){
return mysqli_affected_rows($this->db_connect_id);
}
public function get_insert_id() {
return mysqli_insert_id($this->db_connect_id);
}
public function free_result($q_id) {
if($q_id == ""){
$q_id = $this->q_id;
}
mysqli_free_result($q_id);
}
public function close_db(){
return mysqli_close($this->db_connect_id);
}
public function more_result() {
return mysqli_more_results($this->db_connect_id);
}
public function next_result() {
return mysqli_next_result($this->db_connect_id);
}
public function __construct(){
$this->connect();
}
}
?>
mysqli_fetch_raw($results)
and
mysqli_fetch_array($results)
will give you information about only one raw. and use,
$datos = mysqli_fetch_all($query2)
you can get all output results by adding for loop.
for example.
if you want get all outputs,
<select id="disabledSelect" name="titulo" style="WIDTH: 228px; HEIGHT: 40px" class="form-control">
<?php
for ($i=0 ; $i<=(count($result)-1);$i++){
if ($i==0){$selected="select";} else {$selected=""}
echo '<option value="'. $result[$i][0].'" '.$selected.'>'.$result[$i][2].'</option>';
}
?php
</select>
sorry for my bad English too..

Update Mysql with form

I would like to update a sql table with a html form. I would like to select the element with a drop-down list and later update the values with the form.
Here is my code, the drop-down list and the form works, but I didn't know how to make that the php code get the element that I select.
HTML form:
<?php
require("conectarBD.php");
$select = "SELECT id_serie, nombre FROM series";
$result = $conectar->query($select);
?>
Selecciona la serie que quieres modificar:
<br>
<select>
<?php
while ( $row = $result->fetch_array() )
{
?>
<option value=" <?php echo $row['id_serie'] ?> " >
<?php echo $row['nombre']; ?>
</option>
<?php
}
?>
</select>
<form action="modificar_serie.php" method="post">
<p>
Introduce los cambios a realizar:
</p>
<p>
<label for="textfield">Nombre</label>
<input type="text" name="nom" id="nom" />
<label for="textarea"></label>
</p>
<p>
<label for="textfield">Temporadas</label>
<input type="number" name="temp" id="temp" />
<label for="textarea"></label>
</p>
<p>
<label for="textfield"> Año de estreno</label>
<input type="text" name="est" id="est" />
<label for="textarea"></label>
</p>
<input type="Submit" value="Actualizar">
</form>
PHP:
<?php
require("conectarBD.php");
$nombre = $_POST["nombre"];
$temp = $_POST["temp"];
$est = $_POST["est"];
$query="UPDATE series SET nombre = '.$nombre.', temporadas = '.$temp.', estreno= '.$est.' WHERE nombre='$nombre'";
mysqli_query($conectar,$query);
if(mysqli_affected_rows()>=0){
echo "<p>($nombre) Datos Actualizados<p>";
}else{
echo "<p>($nombre) No se ha podido actualizar en estos momentos<p>";
}
header("Location: ../index.php");
?>
Your select element must be inside form and have a name. Then you will be able to get a value of it from $_POST.

PHP session is not storing any data in my array

It was working, but only on chrome and only on my PC, suddenly it stopped working completely, after I closed and reopened chrome. Now it wont store any data in my session.
http://xeon.spskladno.cz/~filipt/Fourth.php
<?php
session_start();
print_r($_SESSION);
$num1=$_POST["num1"];
$num2=$_POST["num2"];
$action=$_POST["action"];
$memory=$_POST["memory"];
if($action=='+')
$vys=$num1+$num2;
if($action=='-')
$vys=$num1-$num2;
if($action=='*')
$vys=$num1*$num2;
if($action=='/')
$vys=$num1/$num2;
?>
<!DOCTYPE html>
<html><body>
<form action="Fourth.php" method="post">
Cislo1: <br>
<input type="number" name="num1" value="<?php echo $num1;?>" >
<br>
Cislo2: <br>
<input type="number" name="num2" value="<?php echo $num2;?>">
<br>
Akce: <br>
<select name="action" >
<option value="+">Scitani</option>
<option value="-">Odcitani</option>
<option value="*">Nasobeni</option>
<option value="/">Deleni</option>
</select>
<br>
Pocet ulozenych vypoctu:<br>
<input type="number" name="memory" value="<?php echo $memory;?>">
<br><br><br>
<input type="submit" value="Spocti">
</form>
</body>
</html><?php
if((strlen(trim($_POST["num1"]))==0)||(strlen(trim($_POST["num2"]))==0)||(strlen(trim($_POST["memory"]))==0))
die("Vyplnte prosim obe cisla a pocet ulozenych vypoctu.");
if($action=='+'){
echo "Vysledek prikaldu ",$num1,$action,$num2," je ",$vys;
}
if($action=='-'){
echo "Vysledek prikaldu ",$num1,$action,$num2," je ",$vys;
}
if($action=='*'){
echo "Vysledek prikaldu ",$num1,$action,$num2," je ",$vys;
}
if($action=='/'){
echo "Vysledek prikaldu ",$num1,$action,$num2," je ",$vys;
}
$string="$num1$action$num2=$vys";
array_push($_SESSION['vysledky'],$string);
$con=count($_SESSION['vysledky']);
if($con>$memory){
$rozdil=$con-$memory;
for($i=0; $i<$rozdil; $i++)
array_shift($_SESSION['vysledky']);
}
echo "<br>Ulozene vypocty:<br> ";
foreach ($_SESSION['vysledky'] as $value) {
echo "$value <br> ";
}
?>

dropdown selected item not printing

I am trying to print the dropdown selected item. I have well displayed the dropdwon list menu. but when i select an option it doesn't print the option. i have tried in many ways. But not yet got! Please help me, this is my following code.
<form name="choose" method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php
$query="SELECT id_cat,name FROM `fs01_metier_cat` ORDER BY `fs01_metier_cat`.`id_cat`";
$result = mysql_query($query);
?>
<?php
echo "<select name=category></option>";
while($nt=mysql_fetch_array($result)) {
echo "<option value='".$nt['name']."'>".$nt['name']."</option>";
}
echo "</select>";
?>
<input type="submit" name="submit" value="save category" />
</form>
<?php
if($_GET){
echo 'The year selected is'.$_GET['category'];
}
?>
You have issues in your code, try this one instead :
<form name="choose" method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php
$query="SELECT id_cat,name FROM `fs01_metier_cat` ORDER BY `fs01_metier_cat`.`id_cat`";
$result = mysql_query($query);
?>
<select name=category>
<?php
while($nt=mysql_fetch_array($result)) {
echo "<option value='".$nt['name']."'>".$nt['name']."</option>";
}
?>
</select>
<input type="submit" name="submit" value="save category" />
</form>
<?php
if($_GET){
echo 'The year selected is'.$_GET['category'];
}
?>
$_GET['category']
should be
$_POST['category']
Example for javascript:
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var eSelect = document.getElementById('cat');
eSelect.onchange = function() {
document.getElementById("displaytext").innerHTML = "Selected Value: "+this.value;
document.getElementById("displaytext").style.display= 'block';
}
}
</script>
</head>
<body>
<select id="cat" name="cat">
<option value="x">X</option>
<option value="y">Y</option>
<option value="other">Other</option>
</select>
<div id="displaytext" style="display: none;" ></div>
</body>
</html>
​

Categories