PHP putting last inserted row into a session - php

I'm working on a school project, and I'm currently working on a form.
I'm trying to insert the last inserted row from a table in my database into a session, so I can reuse the info when they want to go back to the form to adapt something.
So the data is being inserted into the database, but when I try to put the variable $insertedGegvens into a session, it returns null, and I don't understand why.
I currently have this:
PDO:
public function selectById($id) {
$sql = "SELECT * FROM `gegevens` WHERE `id` = :id";
$stmt = $this->pdo->prepare($sql);
$stmt->bindValue(':id', $id);
$stmt->execute();
}
public function insert($data) {
$errors = $this->validate( $data );
if (empty($errors)) {
$sql = "INSERT INTO `gegevens`
(`naam`, `gemeente`, `postcode`, `adres`,
`huisnr`, `email`, `tel`)
VALUES (:naam, :gemeente, :postcode, :adres,
:huisnr, :email, :tel)";
$stmt = $this->pdo->prepare($sql);
$stmt->bindValue(':naam', $data['naam']);
$stmt->bindValue(':gemeente', $data['gemeente']);
$stmt->bindValue(':postcode', $data['postcode']);
$stmt->bindValue(':adres', $data['adres']);
$stmt->bindValue(':huisnr', $data['huisnr']);
$stmt->bindValue(':email', $data['email']);
$stmt->bindValue(':tel', $data['tel']);
if ($stmt->execute()) {
return $this->selectById($this->pdo->lastInsertId()); //insert returns last row inserted through function selectById
}
}
return false;
}
public function validate( $data ){
$errors = [];
if (!isset($data['naam'])) {
$errors['naam'] = 'Gelieve een naam in te vullen';
}
if (!isset($data['gemeente'])) {
$errors['gemeente'] = 'Gelieve een gemeente in te vullen';
}
if (!isset($data['postcode'])) {
$errors['postcode'] = 'Gelieve een postcode in te vullen';
}
if (empty($data['adres']) ){
$errors['adres'] = 'Gelieve een adres in te vullen';
}
if (empty($data['huisnr']) ){
$errors['huisnr'] = 'Gelieve een huisnummer in te vullen';
}
if (empty($data['email']) ){
$errors['email'] = 'Gelieve een email in te vullen';
}
if (empty($data['tel']) ){
$errors['tel'] = 'Gelieve een telefoonnummer in te vullen';
}
return $errors;
}
if($_POST['action'] == 'toCheckout'){
$insertedGegevens = $this->orderDAO->insert($_POST);
//trying to insert the info it just inserted into a SESSION['user'] so I can reuse this info when user returns to form
$_SESSION['user'] = array();
$_SESSION['user'] = $insertedGegevens;
//$_SESSION['user'] returns null
if (!$insertedGegevens) {
$error = $this->orderDAO->validate($_POST);
$this->set('errors', $error);
}
$_SESSION['user'] = array();
$_SESSION['user'] = $insertedGegevens;
header('Location: index.php?page=checkout');
exit();
}

Related

Database comparison won't work correctly in if() statement

I am sitting at this problem for a lot of time and asked other people around me for help, which I received but didn't solved the problem. I am trying to compare if the username which someone choose in his registration is already in the database, same for the email.
The Problem: If one statement (for example the name) is not in the database, but the email is, it will still insert it into the database. If both statements are equal, it won't insert it.
What I did: I tried 4 main things which I write more or less like this:
Using if($res2_email == $email) { $emailissame = ""; }
else { $emailissame = "no"; } * (same for the name)*
I rewrote the other code to: if(!empty($emailissame && $nameissame)) { insert into database }
if(!$res2_email == $email) { if(!$res2_name == $name) { insert into database } else { echo "Name is the same"; } } else { echo "Email is the same"; }
Echoing the code via $res2_email $res2_name $email $name where the results were as expected the same $res2_email and $email were the same, $res2_name, and $name also.
That's a piece of my code right now which does not work:
$name = $_POST['name'];
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$email = $_POST['email'];
} else {
echo "<span class=\"phpfehlermeldung\">Die angegebene E-Mail Adresse ist keine gültige E-Mail Adresse!</span>";
include "../footer.php";
exit;
}
$passwort = $_POST['passwort'];
$sqlr = $verbindung->prepare("SELECT name, email FROM nutzer WHERE name=? AND email=?");
$sqlr->bind_param("ss", $name, $email);
$sqlr->execute();
$sqlr->bind_result($res2_name, $res2_email);
$sqlr->fetch();
if ($res2_email == $email || $res2_name == $name) {
echo "<span class=\"phpfehlermeldung\">Die E-Mail Adresse oder Name ist bereits genutzt: $name $email.</span>";
} else {
$insertr = $verbindung->prepare("INSERT INTO nutzer (name, email, passwort) VALUES (?, ?, ?)");
$insertr->bind_param("sss", $name, $email, $passwort);
$insertr->execute();
echo "<span class=\"phpfehlermeldung\">Sie haben sich registriert mit $name, $email, $passwort.</span>";
/* Verbindungen schließen */
mysqli_close($verbindung);
$sqlr->close();
$insertr->close();
}
Yes until now the passwords are not hashed, which I will work on in the next days.
This example is for mysqli, that fits with
$sqlr = $verbindung->prepare("SELECT name, email FROM nutzer WHERE name=? OR email=?");
$sqlr->bind_param("ss", $name, $email);
$sqlr->execute();
$sqlr->execute();
$result = $sqlr->get_result();
$user = $result->fetch_array(MYSQLI_ASSOC);
while ($user = $result->fetch_assoc()) {
if($user['email'] == $email || $user['name'] == $name) {
...
}
}
$result->close();
I also changed the AND on your select, because your if also indicates that you don't want either to be true, But this could lead to more than one row
If you really wnat that neither name nor email isthe same ( You must nake the columns unique, that makes it impossible to have them twice

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

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

Function declaring two times error

I'm trying to understand functions. I created a function and i want to call it multiple times. First I do a SQL query, save it in an array and convert it to seconds. The next thing is do a new SQL query (which does his job perfectly fine). When I try to convert this to seconds it goes wrong, I get this error:
Cannot redeclare myfunction() (previously declared in C:\xampp\htdocs\webpagina met input - kopie\try.php:103) in C:\xampp\htdocs\webpagina met input - kopie\try.php on line 103.
Can anyone help?
<?php
$servername = "localhost"; //inloggegevens database
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
// check of er nog genoeg tijd over is en vergelijk met ingevoerde tijd
$sql1 = "SELECT tijd FROM gespeeldeTijd"; // get data with sql query
sqlquery($sql1, $conn, "tijd");
if ($stateLoop == "1") {
convertArrayToMHS($myArray);
hsmToSeconds($sumUren, $sumMinuten, $sumSeconden);
print_r($seconden);
$myArray = [];
$stateLoop == "0";
$sql2 = "SELECT tijd FROM toegelatentijd WHERE naam = 'thomas'"; // get data with sql query
sqlquery($sql2, $conn, "tijd");
if ($stateLoop == "1") {
convertArrayToMHS($myArray);
hsmToSeconds($sumUren, $sumMinuten, $sumSeconden);
print_r($seconden);
$myArray = [];
$stateLoop == "0";
}
} else {
}
// check of er nog een tijd loopt
$sql1 = "SELECT stopTijd FROM gespeeldeTijd ORDER BY ID DESC LIMIT 1"; // get data with sql query
sqlquery($sql1, $conn, "stopTijd");
if ($stateLoop == "1") {
/* print_r($myArray); */
// get time now an compare these to the time asked in sql 1, if time is still not reached get time and display, if time is reached show input field
} else {
}
}
function sqlquery($sql, $conn, $naamtabel) {
global $myArray;
global $stateLoop;
$stateLoop = "0";
$result = $conn->query($sql);
if ($result->num_rows > 0) { // do a while loop to fetch all data to an array
// output data of each row
while ($row = $result->fetch_assoc()) {
$myArray[] = $row["$naamtabel"]; //alle data van kolom "tijd" in een array
/* print_r($myArray); */
}
$stateLoop = "1";
} else { // if there are no results
echo "0 results";
}
}
function convertArrayToMHS($myArray) {
global $sumUren;
global $sumMinuten;
global $sumSeconden;
global $array_product;
function myfunction($value) { //function to do to evry part of the array
global $array_product;
$array_product[] = explode(":", $value); // split the time in hours, minutes, seconds
return $array_product; //bevat alle gesplitte waardes
}
array_walk($myArray, "myfunction"); // walk trough evry part of the array en voer er "myfunction" op uit
/* print_r($array_product); */
/* print_r($totalElements); */
$uren = array_column($array_product, '0'); // zet alle waarden in een aparte array met 0 (uren)
$minuten = array_column($array_product, '1'); // zet alle waarden in een aparte array met 0 (uren)
$seconden = array_column($array_product, '2'); // zet alle waarden in een aparte array met 0 (uren)
$sumUren = 0;
$sumMinuten = 0;
$sumSeconden = 0;
foreach ($uren as $uren) { //tel alle uren van de sql database bijeen
$sumUren = $sumUren + $uren;
}
foreach ($minuten as $minuten) { //tel alle minuten van de sql database bijeen
$sumMinuten = $sumMinuten + $minuten;
}
foreach ($seconden as $seconden) { //tel alle seconden van de sql database bijeen
$sumSeconden = $sumSeconden + $seconden;
}
}
function hsmToSeconds($sumUren, $sumMinuten, $sumSeconden) {
global $seconden;
$seconden = ($sumUren * 3600) + ($sumMinuten * 60) + $sumSeconden; //uren/minuten/seconden omzetten naar seconden
}
?>
You call to convertArrayToMHS twice, every call you declare myfunction.
Put myFunction outside of convertArrayToMHS.

PHP redirecting before finish MySQL insert

I have this code on "insert.php":
if ($stmt = $GLOBALS['mysqli']->prepare("INSERT INTO table1(iduser, title, msg, anonim, ip, iduniversity) VALUES (?,?,?,?,?,?)")) {
$stmt->bind_param("issisi", $_SESSION['iduser'], $_POST['title'], $_POST['msg'], $anonim, getIP(), $_SESSION['iduniversity']);
if ($stmt->execute()) {
$idmsg = $GLOBALS['mysqli']->insert_id;
$i = 0;
$stmt2 = $GLOBALS['mysqli']->prepare("INSERT INTO tag(idmsg, tag) VALUES(?,?)");
foreach ($tags as $tag) {
if ($tag != '') {
$stmt2->bind_param("is", $idmsg, $tag);
if ($stmt2->execute()) {
$i++;
}
}
}
$stmt2->close();
$stmt->close();
mysqli_close($GLOBALS['mysqli']);
sendFile($idmsg);
header("Location: /public/watch_msg.php?idmsg=" . $idmsg);
exit();
} else {
exit("Ops! Ocorreu algum erro. COD1370");
}
} else {
exit("Ops! Ocorreu algum erro. COD1371");
}
So, everything is working fine, except that sometimes when it redirects to "watch_msg.php" the message seems not to be on the database yet. When this happens, as soon as I refresh the page, everything is there!
First thing I thought is that there could be a race-condition somewhere, but I read in another question that PHP is sequential, and as I close both statements and connection before the redirect (so that used tables should be unlocked), why i'm getting this result somethimes? What i'm doing wrong?
Also, no functions outputs anything, but "sendFile" saves an image if the user sends one, so headers should be fine (it also gives me the error when I comment the function).
Code on watch_msg:
$msg = NULL;
$tags = NULL;
$coments = NULL;
$data_high = date("Y-m-d H:i:s");
$iduser;
if ($loggedin) { //If logged in
$idmsg = filter_input(INPUT_GET, 'idmsg', FILTER_SANITIZE_STRING);
$iduser = $_SESSION['iduser'];
$query = "SELECT * FROM table1 WHERE iduser = ? AND idmsg = ? AND datemsg < ?";
$stmt = $GLOBALS['mysqli']->prepare($query);
$stmt->bind_param("iis", $iduser, $idmsg, $data_high);
if ($stmt->execute()) {
$msg = mysqli_fetch_assoc($stmt->get_result());
if ($msg === NULL) {
exit('This message doesn\'t exists');
}
...
} else {
echo "Error.";
}
}

how to insert a query within a class?

I am working on a class where I want to check if everything is filled in and if everything is filled in then insert into the database, but I am stuck on how I can insert within my class so I hope you guys could help me. I never got any errors of this problem.
Here is the code:
<?php
class clsCatCheck
{
private $catName;
public function __construct($catName)
{
$this->setCatName($catName);
}
public function setCatName($catName)
{
$connect = new PDO('mysql:host=hostname;dbname=dbname', "username", "password");
$select = $connect->prepare('SELECT * FROM category');
$row = $select->fetch();
if (isset($_POST['addCat'])) {
if (empty($_POST['catName'])) {
throw new Exception('Geen categorienaam is ingevuld<br />');
}
//if (strlen($_POST['catName'] <= 4)) {
// throw new Exception('De categorienaam moet minimaal 4 letters of langer zijn<br />');
//}
if ($_POST['catName'] == $row[1]) {
throw new Exception('Deze categorienaam bestaat al<br />');
}
}
else {
$query = $connect->prepare("INSERT INTO category (catName) VALUES (:catName = catName)");
$query->bindParam(':catName', $_POST['catName'] ,PDO::PARAM_STR);
$query->execute();
}
$this->catName = $catName;
}
public function getCatName()
{
return $this->catName;
}
}
Already thanks for helping.
If you want more code from me just ask.
You are not binding parameters correctly.
Corrected code:
$query = $connect->prepare("INSERT INTO category (catName) VALUES (:catName)");
$query->bindParam(':catName', $_POST['catName'] ,PDO::PARAM_STR);

Categories