So, I'm getting an id_cliente from another php and I get it correctly from that id. I want to update my database but I can't find a way to do it. I've tried UPDATE, a friend of mine checked the code for syntax error, but I still want to see if any of use were wrong.
Here's my body:
<body>
<div class="maindiv">
<div class="form_div">
<div class="title">
<h2>Insertando datos a la tabla de Cliente.</h2>
</div>
<?php
$id_cliente = $_POST['id_cliente'];
?>
<form action="actualizar.php" method="post">
<?php
$query= "SELECT * FROM cliente WHERE $id_cliente = id_cliente";
include "../conexion/conexion.php";
$sql = mysqli_query($conn, $query);
if(empty($sql)) echo "No se encontró ningún personal que coincida con la búsqueda";
else{
while($row = mysqli_fetch_object($sql)){ ?>
<h2>Llena todos los campos.</h2>
<label>Clave:</label>
<input class="input" name="clave" type="number" value="<?php echo $row->CLAVE ?>">
<label>Nombre:</label>
<input class="input" name="nombre" type="text" value="<?php echo $row->NOMBRE ?>">
<label>Apellido Paterno:</label>
<input class="input" name="apellido_p" type="text" value="<?php echo $row->APELLIDO_P ?>">
<label>Apellido Materno:</label>
<input class="input" name="apellido_m" type="text" value="<?php echo $row->APELLIDO_M ?>">
<label>Direccion:</label>
<textarea cols="25" name="direccion" rows="5"><?php echo $row->DIRECCION ?></textarea><br>
<label>Telefono:</label>
<input class="input" name="telefono" type="text" value="<?php echo $row->TELEFONO ?>">
<label>Correo:</label>
<input class="input" name="correo" type="text" value="<?php echo $row->CORREO ?>">
<label>Fecha de Nacimiento (AA/MM/DD):</label>
<input class="input" name="fecha" type="date" value="<?php echo $row->NACIMIENTO ?>">
<label>Saldo:</label>
<input class="input" name="saldo" type="number" value="<?php echo $row->SALDO ?>">
<?php } $conn->close(); } ?>
<?php
$connection = mysqli_connect("localhost", "root", "");
$db = mysqli_select_db($connection,"cajadeahorros");
error_reporting(0);
if(isset($_POST['submit']))
{
if($_POST['id_cliente'] == "") $_POST['id_cliente'] = "NULL";
$clave = $_POST['clave'];
$nombre = $_POST['nombre'];
$apellido_p = $_POST['apellido_p'];
$apellido_m = $_POST['apellido_m'];
$direccion = $_POST['direccion'];
$telefono = $_POST['telefono'];
$correo = $_POST['correo'];
$fecha = $_POST['fecha'];
$saldo = $_POST['saldo'];
$q="select count(1) from cliente where clave='$clave'";
$r=mysqli_query($connection,$q);
$row=mysqli_fetch_row($r);
if($row[0]>=1)
{
$x = 1;
}
else
{
$x = 0;
}
if($clave !=''&&$nombre !=''&&$apellido_p !=''&&$apellido_m !=''&&$direccion !=''&&$telefono !=''&&$correo !=''&&$fecha !=''&&$saldo !=''&&$x==0)
{
$query = mysqli_query($connection, "update cliente set clave = 'a', nombre = 'a', apellido_p='a', apellido_m='a', direccion ='a', correo='a', nacimiento='a', saldo='a' where id_cliente = '$id_cliente'");
echo "<br/><br/><span>Datos ingresados correctamente.</span>";
}
else
{
echo "<p>No se pudo insertar. <br/> Algunos campos estan vacios o la clave ya existe.</p>";
}
}
mysqli_close($connection);
?>
<input class="submit" name="submit" type="submit" value="Insertar">
</form>
</div>
</div>
</body>
Please change the top select query which you have given like
$query= "SELECT * FROM cliente WHERE $id_cliente = id_cliente";
to
$query= "SELECT * FROM cliente WHERE id_cliente = $id_cliente";
Related
I'm trying to create an option for the user to edit the information in a table I have created using PHP and MySQL. I managed to create this function and the data is being modified, the only problem is when I click the "edit" button on one record of the table, the edit screen always shows all the records from the table, instead of showing only the data I want to modify, how can I solve this?
Here is my code:
<?php
ini_set('default_charset','UTF-8');
$host="localhost";
$username="********";
$password="********";
$db_name="*********";
$con=mysqli_connect("$host", "$username", "$password", "$db_name")or die("cannot connect");
mysqli_set_charset($con,"utf8");
$sql = "SELECT `ID`, `carro`, `datasaida` , `horasaida` , `datachegada`, `horachegada`, `kminicial`, `kmfinal`, `destino`, `motorista` FROM `carro`";
$query = $con->query($sql);
while ($dados = $query->fetch_assoc()) {
$id = $dados["ID"];
$carro = $dados["carro"];
$datasaida = $dados["datasaida"];
$horasaida = $dados["horasaida"];
$datachegada = $dados["datachegada"];
$horachegada = $dados["horachegada"];
$kminicial = $dados["kminicial"];
$kmfinal = $dados["kmfinal"];
$destino = $dados["destino"];
$motorista = $dados["motorista"];
echo "
<form id=\"form1\" name=\"form1\" method=\"post\" action=\"salvar_edicao.php\">
ID: <input name=\"id\" type=\"text\" readonly=\"readonly\" id=\"id\" value=\"$id\" size=\"35\"/><br>
CARRO: <input name=\"carro\" type=\"text\" id=\"id\" value=\"$carro\" size=\"35\"/><br>
DATA DE SAIDA: <input name=\"datasaida\" type=\"text\" id=\"id\" value=\"$datasaida\" size=\"35\"/><br>
HORA DE SAIDA: <input name=\"horasaida\" type=\"text\" id=\"id\" value=\"$horasaida\" size=\"35\"/><br>
DATA DE CHEGADA: <input name=\"datachegada\" type=\"text\" id=\"id\" value=\"$datachegada\" size=\"35\"/><br>
HORA DE CHEGADA: <input name=\"horachegada\" type=\"text\" id=\"id\" value=\"$horachegada\" size=\"30\"/><br>
KM INICIAL: <input name=\"kminicial\" type=\"text\" id=\"id\" value=\"$kminicial\" size=\"35\"/><br>
KM FINAL: <input name=\"kmfinal\" type=\"text\" id=\"id\" value=\"$kmfinal\" size=\"35\"/><br>
DESTINO: <input name=\"destino\" type=\"text\" id=\"id\" value=\"$destino\" size=\"35\"/><br>
MOTORISTA: <input name=\"motorista\" type=\"text\" id=\"id\" value=\"$motorista\" size=\"35\"/><br>
<input type=\"submit\" onclick=\"return confirm('Deseja mesmo editar esse registro?');\" name=\"Submit\" value=\"SALVAR ALTERAÇÕES\" class=\"btnNew\"/>
</form>
";
}
?>
on your edit button, you should also set what information from all the informations they have that they want to edit. The common step here is to supply row id that will be edited:
<a href="edit.php?id=<?php echo $fieldId; ?>">edit</edit>
And on your edit script, you read the id parameter using $_GET['id'] and set it in your query:
$sql = "SELECT `ID`, `carro`, `datasaida` , `horasaida` , `datachegada`, `horachegada`, `kminicial`, `kmfinal`, `destino`, `motorista` FROM `carro` WHERE `ID` = '$id'";
This will make sure that you only get one record instead of the whole tables.
PHP has built in formatting/templating which you could use to improve the format of your code:
<?php
ini_set('default_charset','UTF-8');
$host = "localhost";
$username = "********";
$password = "********";
$db_name = "*********";
$con = mysqli_connect("$host", "$username", "$password", "$db_name")or die("cannot connect");
mysqli_set_charset($con,"utf8");
$sql = "SELECT `ID`, `carro`, `datasaida` , `horasaida` , `datachegada`, `horachegada`, `kminicial`, `kmfinal`, `destino`, `motorista` FROM `carro`";
$query = $con->query($sql);
while($dados = $query->fetch_assoc()){
$id = $dados["ID"];
$carro = $dados["carro"];
$datasaida = $dados["datasaida"];
$horasaida = $dados["horasaida"];
$datachegada = $dados["datachegada"];
$horachegada = $dados["horachegada"];
$kminicial = $dados["kminicial"];
$kmfinal = $dados["kmfinal"];
$destino = $dados["destino"];
$motorista = $dados["motorista"];
// we can make use of PHP's built formatting/templating functionality here
?>
<form id="form1" name="form1" method="post" action="salvar_edicao.php">
ID: <input name="id" type="text" readonly="readonly" id="id" value="<?php echo $id; ?>" size="35"/><br>
CARRO: <input name="carro" type="text" id="carro" value="<?php echo $carro; ?>" size="35"/><br>
DATA DE SAIDA: <input name="datasaida" type="text" id="datasaida" value="<?php echo $datasaida; ?>" size="35"/><br>
HORA DE SAIDA: <input name="horasaida" type="text" id="horasaida" value="<?php echo $horasaida; ?>" size="35"/><br>
DATA DE CHEGADA: <input name="datachegada" type="text" id="datachegada" value="<?php echo $datachegada; ?>" size="35"/><br>
HORA DE CHEGADA: <input name="horachegada" type="text" id="horachegada" value="<?php echo $horachegada; ?>" size="30"/><br>
KM INICIAL: <input name="kminicial" type="text" id="kminicial" value="<?php echo $kminicial; ?>" size="35"/><br>
KM FINAL: <input name="kmfinal" type="text" id="kmfinal" value="<?php echo $kmfinal; ?>" size="35"/><br>
DESTINO: <input name="destino" type="text" id="destino" value="<?php echo $destino; ?>" size="35"/><br>
MOTORISTA: <input name="motorista" type="text" id="motorista" value="<?php echo $motorista; ?>" size="35"/><br>
<input type="submit" onclick="return confirm('Deseja mesmo editar esse registro?');" name="Submit" value="SALVAR ALTERAÇÕES" class="btnNew"/>
</form>
<?php
}
After submitting the form, your code located in salvar_edicao.php should look something like this:
<?php
ini_set('default_charset','UTF-8');
$host = "localhost";
$username = "********";
$password = "********";
$db_name = "*********";
$con = mysqli_connect("$host", "$username", "$password", "$db_name")or die("cannot connect");
mysqli_set_charset($con,"utf8");
// check that the data has been posted
if(!isset($_POST["id"])){
// No `id` found in post data
die;
}
$sql = "SELECT `ID`, `carro`, `datasaida` , `horasaida` , `datachegada`, `horachegada`, `kminicial`, `kmfinal`, `destino`, `motorista` FROM `carro` WHERE `ID` = ?";
$statement = $con->prepare($sql);
$statement->bind_param('i', $_POST['id']);
$statment->execute();
$query = $statement->get_result();
$dados = $query->fetch_assoc();
if(is_null($dados)){
// No rows exist for this ID
die;
}
// $dados = row in database
// $_POST = data submitted from 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.
I am trying to populate afew fields using a load button when I select from the dropdown list. However, the load button is not working and the php codes look fine to me. So I am wondering which part went wrong.
I am wondering if I should put the load button at AuthorityCode or below the form. However, I have tried both methods and both doesn't work.
<strong>Authority Code: </strong>
<select name=authorityid value=authorityid>Select Authority</option>
<option value = "">Select</option><br/>
<?php
$connection = new mysqli("localhost", "username", "password", "dbname");
$stmt = $connection->prepare("SELECT AuthorityId FROM AuthorityList");
$stmt->execute();
$stmt->bind_result($authorityid);
while($stmt->fetch()){
echo "<option value = '$authorityid'>$authorityid</option>";
}
$stmt->close();
$connection->close();
?>
</select>
<?php
if(isset($_POST["loadbtn"])){
$authorityid = $_POST["authorityid"];
$conn = new mysqli("localhost", "username", "password", "dbname");
$stmt = $conn->prepare("SELECT AuthorityName, Address, TelephoneNo, FaxNo FROM AuthorityList WHERE AuthorityId = '$authorityid'");
$stmt->execute();
$result = mysqli_query($stmt, $conn);
$details = mysqli_fetch_array($result);
$savedName = $details["AuthorityName"];
$savedAddress = $details["Address"];
$savedTel = $details["TelephoneNo"];
$savedFax = $details["FaxNo"];
}
// while ($row = $result->fetch_array(MYSQLI_NUM)){
// $authorityname = $row[0];
// $address = $row[1];
// $telephone = $row[2];
// $fax = $row[3];
// }
?>
<form action="" method="post" >
<input type="submit" value="Load" name="loadbtn"><br/><br/>
<strong>Authority Name: </strong> <input type="text" name="authorityname" value="<?php echo $savedName; ?>"/><br/>
<strong>Address: </strong> <input type="text" name="address" value="<?php echo $savedAddress; ?>"/><br/>
<strong>Telephone No: </strong> <input type="text" name="telephone" value="<?php echo $savedTel; ?>"/><br/>
<strong>Fax No: </strong> <input type="text" name="fax" value="<?php echo $savedFax; ?>"/><br/>
Change form to:
<form action="window.location.reload()" method="post" >
Your select values are not getting submitted as they are not part of the form. Also your 2nd query was not running properly. I've cheanged it below. Please take a look
Try this-
<strong>Authority Code: </strong>
<form action="" method="post" >
<select name="authorityid">Select Authority
<option value = "">Select</option><br/>
<?php
$connection = new mysqli("localhost", "username", "password", "dbname");
$stmt = $connection->prepare("SELECT AuthorityId FROM AuthorityList");
$stmt->execute();
$stmt->bind_result($authorityid);
while($stmt->fetch()){
echo "<option value = '$authorityid'>$authorityid</option>";
}
$stmt->close();
$connection->close();
?>
</select>
<?php
if(isset($_POST["loadbtn"])){
$authorityid = $_POST["authorityid"];
$conn = new mysqli("localhost", "username", "password", "dbname");
$qry = "SELECT AuthorityName, Address, TelephoneNo, FaxNo FROM AuthorityList WHERE AuthorityId = '$authorityid'";
$result = $conn->query($qry);
$details = mysqli_fetch_array($result);
$savedName = $details["AuthorityName"];
$savedAddress = $details["Address"];
$savedTel = $details["TelephoneNo"];
$savedFax = $details["FaxNo"];
}
?>
<input type="submit" value="Load" name="loadbtn"><br/><br/>
<strong>Authority Name: </strong>
<input type="text" name="authorityname" value="<?php echo isset($savedName) ? $savedName : ''; ?>"/>
<br/>
<strong>Address: </strong>
<input type="text" name="address" value="<?php echo isset($savedAddress) ? $savedAddress : ''; ?>"/>
<br/>
<strong>Telephone No: </strong>
<input type="text" name="telephone" value="<?php echo isset($savedTel) ? $savedTel : ''; ?>"/>
<br/>
<strong>Fax No: </strong>
<input type="text" name="fax" value="<?php echo isset($savedFax) ? $savedFax : ''; ?>"/>
<br/>
</form>
Your error seems to be from mysql part of the code. Below you'll find a sample code that has mysql part removed from it and is running-
<!DOCTYPE html>
<html>
<head>
<title>Fix</title>
</head>
<body>
<strong>Authority Code: </strong>
<form action="" method="post" >
<select name="authorityid">Select Authority
<option value = "">Select</option><br/>
<?php
echo "<option value = '123'>123</option>";
echo "<option value = '234'>234</option>";
echo "<option value = '345'>345</option>";
echo "<option value = '456'>456</option>";
?>
</select>
<?php
if(isset($_POST["loadbtn"])){
$authorityid = $_POST["authorityid"];
if ($authorityid == '123') {
$savedName = 'nameTest';
$savedAddress = 'addressTest';
$savedTel = 'telTest';
$savedFax = 'faxTest';
}
}
?>
<input type="submit" value="Load" name="loadbtn"><br/><br/>
<strong>Authority Name: </strong>
<input type="text" name="authorityname" value="<?php echo isset($savedName) ? $savedName : ''; ?>"/>
<br/>
<strong>Address: </strong>
<input type="text" name="address" value="<?php echo isset($savedAddress) ? $savedAddress : ''; ?>"/>
<br/>
<strong>Telephone No: </strong>
<input type="text" name="telephone" value="<?php echo isset($savedTel) ? $savedTel : ''; ?>"/>
<br/>
<strong>Fax No: </strong>
<input type="text" name="fax" value="<?php echo isset($savedFax) ? $savedFax : ''; ?>"/>
<br/>
</form>
</body>
</html>
Edited: changed the mysqli_query function so that it works properly.
So I am trying to use the intel I got on the first $_POST on the second $_POST but when the second occurs the intel from the first is lost, what can I do to overcome this?
<?php
if(isset($_POST['entrar'])) {
$nr_processo = $_POST['nr_processo'];
echo "$nr_processo";
$aluno = mysql_query("SELECT * FROM alunos WHERE nr_processo = '$nr_processo'");
$row = mysql_fetch_array($aluno) or die ("Este numero de processo não está registado " . mysql_error()) ;
$aluno_nome = $row['nome'];
$aluno_ano = $row['ano'];
$aluno_turma = $row['turma'];
$aluno_ciclo = $row['ciclo'];
echo $aluno_nome, $aluno_ano, $aluno_turma, $aluno_ciclo;
}
?>
<form method="post" action="">
<label> A que se deve a tua visita ah biblitoeca?</label><br>
<label> Estudo/pesquisa</label>
<input name="estudo" value="1" type="checkbox">
<br>
<label> Leitura Periódica</label>
<input name="leitura" value="1" type="checkbox">
<br>
<label>Internet</label>
<input name="net" value="1" type="checkbox">
<br>
<label> Audiovisuais</label>
<input name="audiovisuais" value="1" type="checkbox"> <br>
<input name="enviar" value="Enviar" type="submit">
</form>
<?php
if(isset($_POST['enviar'])) {
$estudo = $_POST['estudo'];
$leitura = $_POST['leitura'];
$internet = $_POST['net'];
$audiovisuais = $_POST['audiovisuais'];
echo $aluno_nome;
$data = date('Y-m-d ');
$hora = date('H:i:s');
echo $data, $hora;
mysql_query("INSERT INTO entradas VALUES('', '$nr_processo', '$aluno_ano', '$aluno_turma', '$estudo', '$leitura', '$internet', '$audiovisuais', '$data', '$hora' )") ;
?>
<!-- <META http-equiv="refresh" content="0;URL=http://localhost/registosbib/agradecimento.php"> -->
<?php
}
?>
You post entrar and enviar in the same request or 2 different requests ?
Edit:
The 2 $_POST doesn't conflict
Fix:
Use $_SESSION instead
session_start();
$_SESSION['row'] = $row;
Then in the second $_POST use $_SESSION['row']['nome'] instead of $aluno_nome and other $aluno_* variables
I recently made a code that updates my posts on my blog. It worked perfectly on localhost. But when i uploaded it online it did not work any more. The weird thing is it doesn't even display a error so i have no idea where to look. Can someone please help me ?
require('config.php');
$query = "SELECT * FROM project ORDER BY idproject DESC";
$result = mysqli_query($verbinding, $query ) or die (mysqli_error('kan geen verbinding maken met de database'));
if(isset($_POST['editBut'])){
$editTitle = $_POST['editName'];
$editThis = mysqli_query($verbinding, "SELECT * FROM project WHERE title = '".$editTitle."'");
$values = mysqli_fetch_assoc($editThis);
}
if(isset($_POST['update'])){
$editedTitle = $_POST['newTitle'];
$editedText = $_POST['newTekst'];
$oldTitle = $_POST['oldTitle'];
$date = $_POST['datum'];
$updater = mysqli_query($verbinding, "UPDATE Project SET title='".$editedTitle."', content='".$editedText."' WHERE title='".$oldTitle."' AND datum='".$date."'");
echo $updater;
header('location:editPost.php?id=1');
}
if(isset($_GET['id'])){
echo 'post has been succesfully updated';
}
<?php if(isset($_POST['editBut'])){ ?>
<form action="" method="post">
Title: <input type="text" name="newTitle" value="<?php echo $values['title'] ?>"><br>
Text: <textarea type="text" name="newTekst" id="newTekst"><?php echo $values['content'] ?></textarea><br>
<input type="hidden" value="<?php echo $values['title'] ?>" name="oldTitle">
<input type="hidden" value="<?php echo $values['datum'] ?>" name="datum">
<input type="submit" name="update" value="Edit post">
</form>
<?php } else { ?>
<p>Find the post you want to edit:</p>
<form action="" method="post">
<select name="editName">
<?php
while ($row = mysqli_fetch_assoc($result)) {
?> <option value="<?php echo $row['title'] ?>"><?php echo $row['title'] ?></option>
<?php } ?>
</select>
<input type="submit" name="editBut" value="Choose">
</form>
<?php } ?>
In update query replace your table name with small letter.
replace Project with project