Modify DB row after query PHP - php

I'm trying to modify my DB after a query. My goal is this: query the values, echo them with a little modify form that, if I hit "modify", the values will be modified in the DB. I don't know if I'm being clear enough, so here's my code, maybe it'll help me explain.
<h3>¿Quieres editar tu receta?</h3>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<h3>Introduce tu email: </h3><input type="text" name="email" placeholder="email"/><br/>
<input type="submit" name="editar" value="Buscar mi receta" class="send-btn">
</form>
<?php
date_default_timezone_set('Europe/Madrid');
$link = mysqli_connect("localhost", "root", "root", "db_csw");
if(!$link){
die("Conexion fallida: ". mysqli_error());
}
if(isset($_POST['editar'])){
$email = $_POST["email"];
$query = "SELECT * FROM datosformulario WHERE email LIKE '%".$email."%'";
$res = mysqli_query($link, $query);
if($res !== false && mysqli_num_rows($res) > 0){
while ($aux = mysqli_fetch_array($res)){
$accion = $_SERVER['PHP_SELF'];
$id = $aux['id'];
echo "Nombre de la receta: ".$aux['nombrereceta']."<br>";
echo "Pasos de la receta: ".$aux['pasosreceta']."<br>";
echo "<br><br>";
echo "¿Quieres editar esta receta?<br/>";
echo "<form method='POST' action='".$accion."'>";
echo "<input type='text' name='nombreRecetaEditada' placeholder='Nombre de la receta'/><br/>";
echo "<textarea cols='42' rows='10' name='pasosRecetaEditada' placeholder='Pasos de la receta'></textarea><br/>";
echo "<input type='submit' name='editarReceta' value='Editar' class='send-btn'><br/>";
echo "</form>";
if(isset($_POST["editarReceta"])){
$nombreRecetaEditada = $_POST["nombreRecetaEditada"];
$pasosRecetaEditada = $_POST["pasosRecetaEditada"];
$actualizaReceta = "UPDATE datosformulario SET nombrereceta='$nombreRecetaEditada',pasosreceta='$pasosRecetaEditada' WHERE id=$id";
$exito = mysqli_query($link, $actualizaReceta);
if($exito !== false){
echo "Receta modificada";
} else {
echo "No se pudo modificar la receta";
}
}
}
} else {
echo "El email introducido no se ha usado para enviar ninguna receta. Por favor, prueba de nuevo";
}
}
mysqli_close($link);
?>
Thanks in advance.

The problem is, the control will never reach to this if(isset($_POST["editarReceta"])){ ... block even though you've click on the submit button the update the values in the table. And that's because it has to cross this if(isset($_POST['editar'])){ ... block to reach the former mentioned if block.
The solution is, take this entire if(isset($_POST["editarReceta"])){ ... } outside of the if(isset($_POST['editar'])){ ... } block, like this:
// your code
if(isset($_POST["editarReceta"])){
...
}
if(isset($_POST['editar'])){
...
}
// your code
Also, to get the $id value in the UPDATE query, you have to change the form's action attribute in the following way,
echo "<form method='POST' action='".$accion."?id='".$id.">";
So that you could catch the appropriate $id in the following way,
$id = (int)$_GET['id'];
Here's the complete code,
<h3>¿Quieres editar tu receta?</h3>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<h3>Introduce tu email: </h3><input type="text" name="email" placeholder="email"/><br/>
<input type="submit" name="editar" value="Buscar mi receta" class="send-btn">
</form>
<?php
date_default_timezone_set('Europe/Madrid');
$link = mysqli_connect("localhost", "root", "root", "db_csw");
if(!$link){
die("Conexion fallida: ". mysqli_error());
}
if(isset($_POST["editarReceta"])){
$id = (int)$_GET['id'];
$nombreRecetaEditada = $_POST["nombreRecetaEditada"];
$pasosRecetaEditada = $_POST["pasosRecetaEditada"];
$actualizaReceta = "UPDATE datosformulario SET nombrereceta='$nombreRecetaEditada',pasosreceta='$pasosRecetaEditada' WHERE id=$id";
$exito = mysqli_query($link, $actualizaReceta);
if($exito !== false){
echo "Receta modificada";
} else {
echo "No se pudo modificar la receta";
}
}
if(isset($_POST['editar'])){
$email = $_POST["email"];
$query = "SELECT * FROM datosformulario WHERE email LIKE '%".$email."%'";
$res = mysqli_query($link, $query);
if($res !== false && mysqli_num_rows($res) > 0){
while ($aux = mysqli_fetch_array($res)){
$accion = $_SERVER['PHP_SELF'];
$id = $aux['id'];
echo "Nombre de la receta: ".$aux['nombrereceta']."<br>";
echo "Pasos de la receta: ".$aux['pasosreceta']."<br>";
echo "<br><br>";
echo "¿Quieres editar esta receta?<br/>";
echo "<form method='POST' action='".$accion."?id='".$id.">";
echo "<input type='text' name='nombreRecetaEditada' placeholder='Nombre de la receta'/><br/>";
echo "<textarea cols='42' rows='10' name='pasosRecetaEditada' placeholder='Pasos de la receta'></textarea><br/>";
echo "<input type='submit' name='editarReceta' value='Editar' class='send-btn'><br/>";
echo "</form>";
}
} else {
echo "El email introducido no se ha usado para enviar ninguna receta. Por favor, prueba de nuevo";
}
}
mysqli_close($link);
?>
Sidenote: Learn about prepared statement because right now your queries are susceptible to SQL injection. Also see how you can prevent SQL injection in PHP.

Related

How to use a checkbox list to validate a test?

I have a checkbox list with 10 options ik the image just have 9:
and a db:
How can I compare the input in the checkbox list with the information inside the column requerimientos in my db?, it means values from the checkbox list must contain all of the values from requerimientos and it will happen with every id, just i didn't fill the other values yet, hope this clarify it
This is what I got, if it seems I have no clue what I am doing it can't be more accurate, but I dont give up. XD
<form action="" method="post">
<?php
$query = $mysqli->query("SELECT idclasificacion,clasificacion FROM clasificacion");
while ($rows = $query->fetch_array()) {
echo'<div class="list-group-item" id='. $rows['idclasificacion'] .'>
<label>
<input type="checkbox" name="requerimiento[]" id="" value="'.$rows['clasificacion'].'">'. $rows['clasificacion'] . '
</label>
</div>';
}
?>
<button class="btn btn-primary" type="submit">Ingresar</button>
</form>
<?php
//extrae los requerimiento seleccionados en forma de string, notar que requerimiento va sin []
if (isset($_POST['requerimiento'])){
$requerimientos = implode ( ',', $_POST['requerimiento']);
echo $requerimientos;
}else {
echo'no ha selecionado ningun requerimiento para su evento';
}
echo '<br>';
$query = $mysqli->query("SELECT requerimientos FROM tipologia");
$rows = $query->fetch_assoc();
var_dump($rows);
$requetipo=explode(',', $rows['requerimientos']);
var_dump($requetipo);
$validacion=in_array($requerimientos,$requetipo);
var_dump ($validacion);
?>
tthis code compare the checked options, with the data inside requerimientos and if both are equal returns true if not false.
Now i just need to do the other options hope a for loop will help me XD
<?php
//extrae los requerimiento seleccionados en forma de string, notar que requerimiento va sin []
if (isset($_POST['requerimiento'])){
$requerimientos = implode ( ',', $_POST['requerimiento']);
// echo $requerimientos;
}else {
echo'no ha selecionado ningun requerimiento para su evento';
}
echo '<br>';
$query = $mysqli->query("SELECT requerimientos FROM tipologia where tipologia='Conferencia'");
$rows = $query->fetch_assoc();
if($requerimientos==$rows['requerimientos']){
echo 'right';
}else{
echo 'wrong';
}

PHP - what is wrong here?

I'm making a Car rental system in school and i have run into an issue I cannot fix.
When I have completed my Query to ask for all the cars matching the users search I have a buttun they can click to rent that car and it redirects them to another page. Lets say you want to rent a Ferrari F12 and click on rent. When you get to the other page it says "Rent Opel Corsa" no matter what car i choose. Probably just a silly oversight on my side.
Here is the Search Function
function søk(){
define('DB_HOST', 'db-kurs.hit.no');
define('DB_NAME', 'v15gdb1');
define('DB_USER','v15g1');
define('DB_PASSWORD','pw1');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Kunne ikke koble til MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Kunne ikke koble til MySQL: " . mysql_error());
$sql = mysql_query("SELECT * FROM Biler WHERE Sted= '$_POST[by]' AND Merke = '$_POST[biler]'");
$resultat = $sql;
$mld = "Du har valgt å søke etter en <b>$_POST[biler]</b> i <b>$_POST[by]</b>.";
if ($_POST['by'] == 'Alle'){
$sql = mysql_query("SELECT * FROM Biler WHERE Merke = '$_POST[biler]'");
$resultat = $sql;
$mld = "Du har valgt å søke etter en <b>$_POST[biler]</b> i <b>alle</b> byer.";
}
if ($_POST['biler'] == 'Alle'){
$sql = mysql_query("SELECT * FROM Biler WHERE Sted= '$_POST[by]' ");
$resultat = $sql;
$mld = "Du har valgt å søke etter <b>alle</b> bilene i <b>$_POST[by]</b>.";
}
if ($_POST['by'] == 'Alle' and $_POST['biler'] == 'Alle'){
$sql = mysql_query("SELECT * FROM Biler");
$resultat = $sql;
$mld = "Du har valgt å søke etter <b>alle</b> bilene i <b>alle</b> byene.";
}
echo "<div id='søkmld'>$mld Husk at du må logge inn for å leie en bil.</div>";
while($row = mysql_fetch_array($resultat, MYSQL_ASSOC))
{
$merke = $_SESSION['merke'] = $row['Merke'];
$modell = $_SESSION['modell'] = $row['Modell'];
$reg = $row['RegNr'];
$pris = $row['Dagspris'];
$sted = $row['Sted'];
$status = $row['erLedig'];
$bilde = $row['Bilde'];
$_SESSION['name'] = $merke. " " .$modell;
echo" <div id='bilsøk'>
<div id='biltype'><h3> $merke $modell</div>
<div id='lei'>
<form method='POST' action='leibil.php' name='leibil'>";
if(isset($_SESSION['brukerID'])){
echo"<input type='submit' value='Lei Nå' name='lei $merke $modell'>
</div>
<div id='bilsøktxt'>
<table>
<tr>
<td>RegNr:</td>
<td>$reg</td>
</tr>
<tr>
<td>Pris:</td>
<td>$pris</td>
</tr>
<tr>
<td>Sted:</td>
<td>$sted</td>
</tr>
<tr>
<td>Status:</td>
<td>";
if ($status == 1){
echo'Ledig';}
if ($status == 0){
echo'Utleid';}
echo "</td>
</tr>
</table>
</div>
<div id='søkimg'><center><img src='images/cars/$bilde.jpg'></center></div>
</div>
";
}
}}
And here is the div on the page you are redirected to:
<div id="hoved">
<?php
echo"<h1>Lei $_SESSION[name]</h1>"
?>
<?php
status();
?> <hr/>
</div>
The Status() function is set just so you know.
#dbinns66 is correct, you are inconsistent with your session and post variables and this could cause problems.
Also, a stab in the dark here...
When you do:
while($row = mysql_fetch_array($resultat, MYSQL_ASSOC))
What happens if you have more than 1 row?
Lets say your query returns 2 rows. When you do:
$merke = $_SESSION['merke'] = $row['Merke'];
$modell = $_SESSION['modell'] = $row['Modell'];
...
$_SESSION['name'] = $merke. " " .$modell;
$_SESSION['name'] will always contain the make and model of the car that is in the last row of your query (in this case, row 2).
Anyway...
To fix this, try adding:
...
echo"<input type='submit' value='Lei Nå' name='lei $merke $modell'>
<input type='hidden' value='$merke $modell' name='makeAndModel'>
...
In your redirected page (leibil.php):
<div id="hoved">
<?php
echo"<h1>Lei " . $_POST['makeAndModel'] . "</h1>"
?>
...
Close your form in your first echo statement:
...
<div id='søkimg'><center><img src='images/cars/$bilde.jpg'></center
</div>
</form>
...
For starters, could you try changing
$_SESSION[name]
to
$_SESSION["name"]
Also, I noticed in building your SQL you have clauses like
... Sted= '$_POST[by]' AND ...
Since "by" is the hash key of the value you're looking for, I'd try changing those to be more like
... Sted= '" . $_POST["by"] . "' AND

Send variable php for method post

I get a var called $cobro in this module php, and i need this variable for calculate a subtraction of a number insert in a input called $vuelto. When i send the form the var $cobro is eliminated and i cant execute the subtraction.
Help, and thx !
<?php
// Disponible desde PHP 4.1.0
date_default_timezone_set("America/Santiago");
if(isset($_POST['fecha'])){
$fecha = date("Y-m-d G:i:s",strtotime($_POST['fecha']));
}
$date1 = strtotime($fecha);
$date2 = time();
$subTime = $date2-$date1;
$y = ($subTime/(60*60*24*365));
$d = ($subTime/(60*60*24))%365;
$h = ($subTime/(60*60))%24;
$m = ($subTime/60)%60;
echo "Diferencia entre ".$fecha." y ".date('Y-m-d H:i:s',$date2)." es:<br/>";
//echo $y." annos<br/>";
echo $d." dias<br/>";
echo $h." horas<br/>";
echo $m." minutos<br/>";
$cobro =0;
$fecha_em= date('Y-m-d H:i:s',$date2);
$h = $h + $m/60 +$d*24;
$cobro = $h*600;
if($cobro<0)
$cobro = $cobro*-1;
if($h < 1)
echo "Debe pagar el minimo: $600";
else
echo "Debe pagar: $".$cobro;
$conexion = mysql_connect("localhost","grupo2","face2014");
mysql_select_db("sisace",$conexion);
/*if ($conexion==0)
echo "Lo sentimos, no se ha podido conectar con la MySQL";
else {
echo "Se logró conectar con MySQL";
echo "<br>";}
*/
$sql="INSERT INTO boleta(fecha_emision,fecha_ingreso,num_boleta,valor_total) ".
"VALUES('$fecha_em','$fecha','1','$cobro')";
mysql_query($sql);
if(isset($_POST['submit'])) {
$vuelto = $_POST['vuelto'];
$vuelto = $vuelto -$cobro;
echo "Su vuelto es el siguiente:";
echo $vuelto;
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="number" name="vuelto"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
You didn't put it in Form use input hidden to post it
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="number" name="vuelto"><br>
<input type="hidden" name="cobro" value="<?php echo $cobro; ?>">
<input type="submit" name="submit" value="Submit Form"><br>
</form>
That's how you can pass cobro variable value which will be available in $_POST['cobro']

mysqli_real_escape_query, query seems ok, but nothing written in database

I have a form, method="post" where users can input info like their name and email, that then get's inserted in a database. For safety I tried to use mysqli_real_escape_string.
Now, the query says it worked but no data get's inserted in my database. Without the escape everything worked allright too (except for not being escaped)
CODE:
(Updated missing quote, it's there in my original code, so that's not the problem. Sry for that)
if(isset($_POST['submit'])) {
$email = explode('#',$_POST['mail']); //explode because I only need the prefix
$maila = mysqli_real_escape_string($link,$email[0]);
$name = mysqli_real_escape_string($link,$_POST['name']);
$query = "INSERT INTO base(mail,name) VALUES ('$maila','$name')";
if(mysqli_query($link,$query)) {
echo "SUCCES";
}
else {
echo "FAIL";}
}
So when I process the query, SUCCES comes up but the mail and name don't arrive in my table.
I googled and searched here, but couldn't find a solution (excuse me if I overlooked it). I also hope I posted enough of my code.
Extra info:
Before the SQL-query goes into action the form is checked in a way like
if($_POST['name'] == null){echo "an error message";}
EDIT; FULL CODE (I am aware that there are mistakes/stupid things in my if-statements, but these work fine without escaping so I will check these later)
<?php
if(isset($_POST['submit'])) {
if($_POST['ios'] == null ) {$resios = 0;} else {$resios = $_POST['ios'];}
if($_POST['android'] == null) {$resand = 0;} else {$resand = $_POST['android'];}
if($_POST['windows'] == null) {$reswin = 0;} else {$reswin = $_POST['windows'];}
//Check for errors
if($_POST['naam'] == null) {echo "<span class=\"error\">Gelieve een naam in te vullen</span><br />";}
if($_POST['opleiding'] == 0) {echo "<span class=\"error\">Selecteer een opleiding</span><br />";}
if($resios > $ios) {$resios = $ios; echo "<span class=\"error\">Aantal iOS tablets overschreden. Maximum " . $ios . " tablets beschikbaar.</span><br />";}
if($resand > $android) {$resand = $android; echo "<span class=\"error\">Aantal Android tablets overschreden. Maximum " . $android . " tablets beschikbaar.</span><br />";}
if($reswin > $windows) {$reswin = $reswin; echo "<span class=\"error\">Aantal Windows tablets overschreden. Maximum " . $windows . " tablets beschikbaar.</span><br />";}
if($resios < 0) {$resios = 0; echo "<span class=\"error\">Aantal tablets kan niet lager zijn dan 0!</span><br />";}
if($resand < 0) {$resand = 0; echo "<span class=\"error\">Aantal tablets kan niet lager zijn dan 0!</span><br />";}
if($reswin < 0) {$reswin = 0; echo "<span class=\"error\">Aantal tablets kan niet lager zijn dan 0!</span><br />";}
if($_POST['terms'] != 'on') {echo "<span class=\"error\">Reglement moet aanvaard worden.</span><br />";}
if($resios == 0 && $resand == 0 && $reswin == 0) {echo "<span class=\"error\">Er moet minstens 1 tablet gereserveerd worden</span>";}
else {
//ESCAPE + INSERT
$email = explode('#',$_POST['mail']);
$maila = mysqli_real_escape_string($link,$email[0]);
$opleiding = mysqli_real_escape_string($link,$_POST['opleiding']);
$naam = mysqli_real_escape_string($link,$_POST['naam']);
$datum = mysqli_real_escape_string($link,$datum);
$resios = mysqli_real_escape_string($link,$resios);
$resand = mysqli_real_escape_string($link,$resand);
$reswin = mysqli_real_escape_string($link,$reswin);
$opmerking = mysqli_real_escape_string($link,$_POST['opmerking']);
$query = "INSERT INTO reservaties(oplid,naam,datum,ios,android,windows,emailname,opmerking) VALUES ('$opleiding','$naam','$datum','$resios','$resand', '$reswin','$maila', '$opmerking')";
if(mysqli_query($link,$query)) {
echo "<p class=\"succes\">U hebt succesvol " . $resios . " iOS-tablets, " . $resand . " Android-tablets en " . $reswin . " Windows-tablets gereserveerd op " . $disdate . "</p>";
echo "<p>Een bevesting van uw reservatie via mail? <form style=\"display:inline;\" target=\"_blank\" action=\"print.php\" method=\"post\"><input type=\"text\" name=\"mail\" value=\"".$maila."\" />#arteveldehs.be <input type=\"hidden\" name=\"naam\" value=\"".$_POST['naam']."\"/><input type=\"hidden\" name=\"datum\" value=\"". $datum . "\"/><input type=\"submit\" name=\"print\" value=\"mail\"></form></p>";
}
else {
echo "<p class=\"error\">Er is een fout opgetreden. Probeer opnieuw, of neem contact op met de Mediatheek.</p>";}
}
}
?>
<!-- my form-->
<form action="#" method="post">
<table>
<tr><td colspan="3"><span class="required">*</span> = verplicht veld</td></tr>
<tr><td>Naam:<span class="required">*</span></td><td><input type="text" name="naam" placeholder="Naam" /></td></tr>
<tr><td>Email:</td><td><input type="text" name="mail" placeholder="voornaam.naam" />#arteveldehs.be</td></tr>
<tr><td>Opleiding:<span class="required">*</span></td><td colspan="2">
<select name="opleiding">
<option value="0">Selecteer een opleiding</option>
<?php
$sql2 = "SELECT SUM(ios) as iostotal,SUM(android) as androidtotal,SUM(windows) as windowstotal FROM reservaties WHERE '$datum' = datum";
$check2 = mysqli_query($link,$sql2) or die(mysql_error());
while ($free2 = mysqli_fetch_array($check2)) {
$iosall = 16;
$andall = 18;
$winall = 20;
$ios2 = $iosall - $free2['iostotal'];
$android2 = $andall - $free2['androidtotal'];
$windows2 = $winall - $free2['windowstotal'];
}
$opleidingen = "SELECT * FROM opleidingen";
$values = mysqli_query($link,$opleidingen) or die(mysql_error());
while ($row = mysqli_fetch_array($values)) {
$oplid = $row['oplid'];$opleiding = $row['opleiding'];
echo "<option value=\"".$oplid."\">".$opleiding."</option>";
}
?>
</select>
</td></tr>
<tr><td>Aantal iOS</td><td><input type="text" name="ios" placeholder="<?= $ios2;?>" ><span class="max">(maximum <?= $ios2;?> beschikbaar)</span></td></tr>
<tr><td>Aantal Android</td><td><input type="text" name="android" placeholder="<?= $android2;?>" ><span class="max">(maximum <?= $android2;?> beschikbaar)</span></td></tr>
<tr><td>Aantal Windows</td><td><input type="text" name="windows" placeholder="<?= $windows2;?>" ><span class="max">(maximum <?= $windows2;?> beschikbaar)</span></td></tr>
<tr><td>Opmerking:</td><td colspan="2"><textarea maxlength="512" rows="5" cols="50" name="opmerking" placeholder="Bv. Tijdstip van oppikken/terugbrengen - vraag aan de mediatheek - ..." ></textarea></td></tr></table>
<input type="checkbox" name="terms" value="on" /> Hiermee verklaar ik me akkoord met het <a target="_blank" href="reglement.php">reglement</a> dat geldt voor het gebruik van deze tablets.<span class="required">*</span>
<p><input type="submit" name="submit" value="Reserveer"/></p>
</form>
<?php }
?>
DATABASE reservaties
resid int(9) PRIMARY KEY
oplid int(9)
naam varchar(55) latin1_swedish_ci
datum date
ios varchar(3)
android varchar(3)
windows varchar(3)
emailname
opmerking varchar(512) latin1_swedish_ci
As per OP's original posted question
You have a missing quote for your query:
$query = "INSERT INTO base(mail,name) VALUES ('$maila','$name') ;
// right there --^
do:
$query = "INSERT INTO base(mail,name) VALUES ('$maila','$name')";
Using error reporting would have helped shown the error http://www.php.net/mysqli_error
Since no error was thrown (at you), this tells me that you are not using error reporting.
if (!mysqli_query($link,$query))
{
die('Error: ' . mysqli_error($link));
}
These or die(mysql_error()) need to be changed to or die(mysqli_error()) since mysql_* and mysqli_* based functions do not mix with each other.
Try this, You have missed to close "
$query = "INSERT INTO `base` (`mail`,`name`) VALUES ('$maila','$name')";
you have missed end " in your query string.
replace this line:
$query = "INSERT INTO base(mail,name) VALUES ('$maila','$name');
by this:
$query = "INSERT INTO base(mail,name) VALUES ('$maila','$name')";

INT field cannot be used in MySQL query

I am having this annoying problem with my query:
I have the table tbl_profissao with the fields
idtbl_profissao (INT(11), A.I.,UNSIGNED, NOT NULL),
cbo (INT(6), UNSIGNED, ZERO FILL) and
profissao (VARCHAR(110)).
I split my query into two PHP pages - profissao_busca.php and profissao_busca_input.php, with the following codes:
For profissao_busca.php:
<?php include "header.php"; ?>
<body>
<h2>PESQUISA: PROFISSÃO (CBO) </h2>
<form id="form_profissao_busca" method="post" action="profissao_busca.php?go">
<p>Por favor, escreva o número CBO da profissão que quer encontrar:<br/><br/>
<input name="busca_cbo" type="text" id="busca_cbo" size="11" maxlength="11" />
<input name="submit" type="submit" value="PROCURAR" /></p>
</form>
<?php
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("/^[ a-zA-Z]+/", $_POST['busca_cbo'])){
$name=$_POST['busca_cbo'];
$db=mysql_connect ("localhost", "root", "root") or die ('Não foi possível conectar-se ao Banco de Dados (erro No.): ' . mysql_error());
$mydb=mysql_select_db("grcc_db_pr");
$sql="SELECT idtbl_profissao, cbo, profissao FROM tbl_profissao WHERE profissao LIKE '%$name%' OR idtbl_profissao LIKE '%$name%' OR cbo LIKE '%$name%'";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)){
$Pessoa=$row['cbo'];
$ident=$row['idtbl_profissao'];
$prof=$row['profissao'];
echo "<ul>\n";
echo "<li> CBO requisitado: " . $Pessoa . "</li><li> Identificador: ". $ident . "</li><li>Ocupação:" . $prof . "</li><li>
<form id=\"form_profissao_busca\" method=\"post\" action=\"profissao_busca_input.php?go\">
<input name=\"button\" type=\"submit\" value=\"BUSCAR ESTE CBO\" />
<input name=\"busca_cbo\" type=\"hidden\" value=\"". $ident. "\" /></form></li>\n";
echo "</ul>";
}
}
else{
echo "<p>Este número não existe no Banco de Dados</p>";
}
}
}
?>
</body>
</html>
And for profissao_busca_input.php:
<?php include "header.php";
$nome_proc = $_POST['busca_cbo'];
// ================== Dados pessoais e documentos
$listagem = "SELECT idtbl_profissao, cbo, profissao FROM tbl_profissao WHERE profissao LIKE '%$name%' OR idtbl_profissao LIKE '%$name%' OR cbo LIKE '%$name%'";
$resultado = mysql_query($listagem);
$listagem = mysql_fetch_array($resultado);
print "<ul><li> CBO requisitado: $listagem[1] </li><li> Identificador: $listagem[0] </li><li>Ocupação: $listagem[2] </li></ul>";
Having a small sample of the table as:
idtbl_profissao,cbo,profissao
1,'010205','Oficial da aeronáutica'
2,'010210','Oficial do exército'
3,'010210','X5020'
4,'010215','Oficial da marinha'
5,'010215','X6020'
6,'010215','X6030'
The problem is that when I put any value belonging to "cbo" column the result is "Este número não existe no Banco de Dados" (meaning the value does not exist in the Database). Whenever I put either a word or alphanumeric value from column "profissao" it works fine.
Now I don't know what is going on, or if I missed something because "cbo" is in INT format.
Anyway, thank you in advance for your attention.
Nicole

Categories