mysqli_real_escape_query, query seems ok, but nothing written in database - php

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')";

Related

My SQL Update query won't update the specified record [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(2 answers)
Closed 3 years ago.
I'm making a system where you can assign guests to certain rooms. To unassign a guest, two UPDATE queries must be executed in two different tables, but only one of these is actually executing. The one that doesn't work, doesn't put out an error message, but doesn't seem to do anything.
I've already printed out all the variables I'm using in my query to check for mistakes, but I haven't found any data in those which was wrong. I also checked if there were errors in my query using phpMyAdmin, but they properly executed there. I used the same type of method on another page, updating something else, and that worked. Could someone take a look in my code and tell me what I've done wrong?
Thanks in advance!
if(isset($_GET['view'])) {
$viewid = $_GET['view'];
$sql = "SELECT * FROM renterinfo LEFT JOIN apartments ON apartments.renterid = renterinfo.renterid WHERE renterinfo.renterid = $viewid";
$xresult = mysqli_query($conn, $sql);
$xrow = mysqli_fetch_array($xresult);
}
$freeroomquery = "SELECT * FROM apartments WHERE status = 1 ORDER BY apartmentno ASC";
$freerooms = mysqli_query($conn, $freeroomquery);
$rentername = $xrow['name'];
$renteremail = $xrow['email'];
$roomno = $xrow['apartmentno'];
$enddate = $xrow['leaveroom'];
if(isset($_POST['submit'])){
//------------------------------------
$name = $_POST['newNaam'];
$email = $_POST['newEmail'];
$room = $_POST['newKamer'];
$leaveroom = $_POST['newEinde'];
$insertSql = "UPDATE renterinfo SET name = '$name', email = '$email', leaveroom = '$leaveroom'";
$updateRoom = "UPDATE apartments SET renterid = NULL WHERE apartmentno = '$roomno'";
The second UPDATE query doesn't update the renterid. The first UPDATE query does work.
if ($conn->query($insertSql) === TRUE) {
$success = "Huurder <strong>'" . $name . " - CobbenCampus'</strong> is succesvol toegevoegd.";
} else {
$error = "Er is een fout opgetreden bij het toevoegen van appartement <strong>'" . $apartmentno . " - CobbenCampus'</strong>. Zijn alle velden ingevuld?<br><strong>Foutmelding:</strong> " . $sql . "<br>" . $conn->error;
}
if ($conn->query($updateRoom) === TRUE) {
echo "Succeeded.";
} else {
echo "Query unsuccessfull.";
}
$conn->close();
}
HTML-code:
<form action="viewrenter.php" method="POST" enctype="multipart/form-data">
<label id="first">Voor- en achternaam huurder:</label><br>
<input type="text" name="newNaam" value="<?php echo $rentername ?>"><br><br>
<hr class="line-black">
<label id="first">E-mailadres van huurder:</label><br>
<input type="text" name="newEmail" value="<?php echo $renteremail ?>"><br><br>
<hr class="line-black">
<label id="first">Kamernummer:</label><br/>
<p>Een kamer toewijzen aan een huurder, zal de kamer automatisch op bezet zetten.</p>
<select name="newKamer">
<option value="<?php echo $roomno ?>"><?php echo $roomno ?></option>
<option value="0">Geen kamer</option>
<?php
while($rooms = mysqli_fetch_array($freerooms)) {
echo "<option value='" . $rooms['apartmentno'] . "'>" . $rooms['apartmentno'] . "</option>";
}
?>
</select><br><br>
<hr class="line-black">
<label id="first">Afloopdatum huurdersovereenkomst:</label><br>
<input type="text" name="newEinde" placeholder="Als: 25-04-2019" value="<?php echo $enddate ?>"><br><br>
<button class="spaced btn btn-primary btn-wide" type="submit" name="submit">Voeg huurder toe</button>
<hr class="bigspacer">
</form>
UPDATE apartments SET `renterid` = NULL WHERE `apartmentno` = `$roomno`
Write query like this. I think it will work.

Modify DB row after query 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.

Inserting checkbox values into multiple rows

I have an echo of a number of groups a user is a member of.
It will output multiple checkboxes. The value of the checkboxes (groupid)+ 2 hidden values need to be inserted into a row in a new table.
How do I insert the values per checkbox into separate rows?
<?php
$user=$_SESSION['SESS_USERID'];
if(isset($_REQUEST['user'])){
$user = preg_replace('#[^a-z0-9]#i', '', $_GET['user']);
}
if(isset($_REQUEST['id'])){
$id = preg_replace('#[^a-z0-9]#i', '', $_GET['id']);
}
$sql="SELECT * FROM groepsleden,groepen,werken WHERE groepsleden.groepid=groepen.groepid
AND groepsleden.userid='$user'AND werken.werkid='$id' ORDER BY groeplidid DESC ";
$result = $conn->query($sql) or die ("The query could not be completed. try again");
if ($result->num_rows > 0) {
echo" <table>";
while ($row = $result->fetch_assoc()) {
echo"<tr>
<td bgcolor='#1E1E1E'> </td>
<td bgcolor='#1E1E1E'><div align='right'>
<input name='groepid' type='checkbox' value=" . $row['groepid'] . ">
<input type='hidden' name='werkid' value=" . $row['werkid'] . ">
<input type='hidden' name='userid' value=" . $row['userid'] . ">
</div></td>
<td bgcolor='#1E1E1E'>Paats dit werk in <a href='groep.php?
id=" . $row['groepid'] . "'</a>".$row["groepsnaam"]."</span></td></tr></table>
}
}
?>
<?php
$sql=$dbo->prepare("INSERT INTO groepwerken(werkid,groepid,userid)
VALUES ('$werkid','$groepid','$user')");
$sql->bindParam(':werkid',$werkid,PDO::PARAM_INT);
$sql->bindParam(':groepid',$groepid,PDO::PARAM_INT);
$sql->bindParam(':userid',$userid,PDO::PARAM_INT);
Veldnamen als array ....
name="groepid[]"
name='werkid[]'
name='userid[]'
vervolgens kun je met foreach door deze waarden heen loopen
$werkid = $_POST['werkid'];
$userid = $_POST['userid'];
$x = 0;// teller zodat we juiste element kunnen selecteren
foreach($_POST['groepid'] as $groepen)
{
if($groepen!=="") // als niet leeg is
{
$juisterwerkid = $werkid[$x];
$juisteuserid= $userid[$x];
$degroep = $groepen;
$x++; // teller ophogen adhv element
echo "Groep: ".$groepen." juisterwerkid: ".$juisterwerkid." juisteuserid: ".$juisteuserid."";
}
}
zoiets zou moeten werken :)

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

Insert into Mysql and get unique id [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have following:
index.php
<form method="get" action="rezultat.php" name="form-area" id="form-area" class="form-area" />
<h4>Informatii despre prieten</h4>
<input type="text" id="name" name="nu" placeholder="" maxlength="25" required />
<input type="text" id="name" name="pr" placeholder="" maxlength="25" required />
<input type="text" id="name" name="va" placeholder="" maxlength="2" required />
<input type="text" id="name" name="lo" placeholder="" maxlength="25" required />
<h4>Informatii despre tine</h4>
<input type="text" id="name" name="np" placeholder="" maxlength="25" required />
<input type="text" id="name" name="pn" placeholder="" maxlength="4" required />
<select name="stire" required >
<option value="Nu ai selectat">Selecteaza</option>
<option value="0">................................ </option>
<option value="Bautor de sperma">[MASCULIN] - Bautor de sperma </option>
<option value="Protest in chiloti">[MASCULIN] - Protest in chiloti </option>
<option value="Si-a taiat penisul">[MASCULIN] - Si-a taiat penisul </option>
<option value="Masturbare in public">[MASCULIN] - Masturbare in public </option>
<option value="Fan Facebook">[MASCULIN] - Fan Facebook </option>
<option value="0">................................ </option>
<option value="Prostituata anului">[FEMININ] - Prostituata anului </option>
<option value="Cu sanii la vedere">[FEMININ] - Cu sanii la vedere </option>
<option value="Sex oral in public">[FEMININ] - Sex oral in public </option>
<option value="A violat un mos">[FEMININ] - A violat un mos </option>
<option value="Miss Urzica">[FEMININ] - Miss Urzica </option>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
rezultat.php
<?php include 'config.php'; include 'colectare.php'; ?>
<? echo $link; ?> //that show url link
config.php
<?php
$host="localhost";
$user_name="USER";
$pwd="PWD";
$database_name="DB";
$conexiune = mysql_connect($host,$user_name,$pwd) or die("Nu ma pot conecta la MySQL!");
mysql_select_db($database_name, $conexiune) or die("Nu gasesc baza de date");
$adresa="http://site.com/";
?>
colectare.php
<?
$host="localhost";
$user_name="USER";
$pwd="PWD";
$database_name="DB";
$db=mysql_connect($host, $user_name, $pwd);
if (mysql_error() > "") print mysql_error() . "<br>";
mysql_select_db($database_name, $db);
if (mysql_error() > "") print mysql_error() . "<br>";
$find = array ("/ /");
$replace = array ("+");
$link = $adresa.'stiri.php? pn='.ucwords($_GET["pn"]).'&nu='.ucwords($_GET["nu"]).'&pr='.ucwords($_GET["pr"]).'&va='.ucwords($_GET["va"]).'&lo='.ucwords($_GET["lo"]).'&stire='.$_GET["stire"];
$link = preg_replace($find,$replace,$link);
$stire = $_GET["stire"];
$np = htmlentities($_GET['np'], ENT_QUOTES | ENT_HTML5);
$pn = $_GET["pn"];
$datetime = gmDate('Y-m-d H:i:s');
$query = "insert into stiri (url, stire, np, pn, hits, datetime) values ('" . $link . "', '" . $stire . "', '" . $np . "', '" . $pn . "', '" . $hits . "', NOW())";
$result = mysql_query($query);
?>
stiri.php
<? include_once "config.php"; ?>
<?
$find = array ("+");
$replace = array ("/ /");
$pn = ucwords($_GET["pn"]);
$nu = ucwords($_GET["nu"]);
$pr = ucwords($_GET["pr"]);
$va = ucwords($_GET["va"]);
$lo = ucwords($_GET["lo"]);
$stire = $_GET["stire"];
?>
<?php
if($stire == "Bautor de sperma"){ // TITLUL FARSEI
echo include("bautor-de-sperma.php"); // PAGINA PHP A FARSEI
}
elseif($stire == "Protest in chiloti"){ // TITLUL FARSEI
echo include("protest.php"); // PAGINA PHP A FARSEI
}
elseif($stire == "Si-a taiat penisul"){ // TITLUL FARSEI
echo include("taiat.php"); // PAGINA PHP A FARSEI
}
elseif($stire == "Masturbare in public"){ // TITLUL FARSEI
echo include("masturbare.php"); // PAGINA PHP A FARSEI
}
elseif($stire == "Fan Facebook"){ // TITLUL FARSEI
echo include("facebook.php"); // PAGINA PHP A FARSEI
}
elseif($stire == "Prostituata anului"){ // TITLUL FARSEI
echo include("prostituata.php"); // PAGINA PHP A FARSEI
}
elseif($stire == "Cu sanii la vedere"){ // TITLUL FARSEI
echo include("sani.php"); // PAGINA PHP A FARSEI
}
elseif($stire == "Sex oral in public"){ // TITLUL FARSEI
echo include("sex.php"); // PAGINA PHP A FARSEI
}
elseif($stire == "A violat un mos"){ // TITLUL FARSEI
echo include("viol.php"); // PAGINA PHP A FARSEI
}
elseif($stire == "Miss Urzica"){
echo include("urzica.php");
}
else
{
echo "Ne pare rau, insa aceasta stire nu mai exista. Vezi mai multe <a href='http://site.ro'>AICI</a>";
}
?>
and i give u and one page, urzica.php for example wich contain following::
<? echo $nu; ?> , <? echo $pr; ?> , <? echo $va; ?> , <? echo $lo; ?>
With that metod, all informations are stored in database, but link it's show all informations, cuz i use get method .
The link its offered like that:
http://site.ro/stiri.php?pn=SOMETHING&nu=SOMETHING&pr=SOMETHING&va=SOMETHING&lo=SOMETHING&stire=SELECTED-ONE
I want to use post method, and that complicated my brain, and to show me something like that:
http://site.ro/stire.php?nume=NAME-FROM-SELECT-FORM
I hope to understand something guys
I'm not 100% certain what you're after, but this MySQL class should help. Basically, all your operations on the database go through here, and you will get that unique id you want on MySQL INSERT commands:
https://gist.github.com/jbnunn/6297071
To use it, set up your connection parameters:
$db_host = 'localhost';
$db_username = 'USER';
$db_password = 'PWD';
$db_database = 'DB';
$GLOBALS['db'] = new MySQL($db_host, $db_username, $db_password, $db_database);
if(!function_exists("getDB")) {
function getDB() {
return($GLOBALS['db']);
}
}
Then, in your code, require that MySQL class,
require_once('mysql.php')
and make inserts like:
$db = getDB();
$id = $db->insert("insert into stiri (url, stire, np, pn, hits, datetime) values ('" . $link . "', '" . $stire . "', '" . $np . "', '" . $pn . "', '" . $hits . "', NOW())");
and get the row's ID from the $id variable.
To get data out of your database, you could make queries via methods like this:
$result = $db->execute("SELECT * FROM stiri WHERE id = '$id'");

Categories