简体   繁体   中英

cant store session variable into database

I have in seassion stored variable. I want to insert session variable and other informations filled through form into table. I got message that it was created but nothing shows in table.

I want to take session variable and store it into "username" i tried $username=$r['username']; but doesnt work.

<?php
    session_start();
    if($_SESSION['user']==''){
        header("Location:login.php");
    }else{
        $dbh=new PDO('mysql:dbname=mydb;host=127.0.0.1', 'myusername', 'mypassword');


    $sql=$dbh->prepare("SELECT * FROM users WHERE id=?");
    $sql->execute(array($_SESSION['user']));
    while($r=$sql->fetch()){

    $username=$r['username'];  <-im not sure if this is correct.
    $ime=$_POST['ime'];
    $priimek=$_POST['priimek'];
    $email=$_POST['email'];
    $izob=$_POST['izob'];
    $izk=$_POST['izk'];
    $prib=$_POST['prib'];
    $opis=$_POST['opis'];
        $sql = "INSERT INTO profil (ime, priimek, email, izob, izk, prib, opis) VALUES( `username`,`ime` , `priimek ` , `email` , `izob` , `izk` , `prib` , `opis`)";

        try {
            $dbh->exec($sql);
            echo " created successfully";
        } catch(PDOException $e) {
            echo $sql . "<br>" . $e->getMessage();
        }
    }

    $conn = null;
}
?>

CREATE TABLE profil(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        username VARCHAR(10),
        ime VARCHAR(10) NOT NULL,
        priimek VARCHAR(10) NOT NULL,
        email VARCHAR(20),
        izob VARCHAR(20),
        izk VARCHAR(10),
        prib VARCHAR(10),
        opis VARCHAR(100),
);

thanks for help

Two problems:

First, you only specified 7 column names in the insert list, but you gave 8 values. Most importantly, the column name you failed to specify was the username column, which is what you are asking about. Second, you should be using the actual PHP variables in the insert, not the column names escaped in backticks. Try the following:

$sql = "INSERT INTO profil (username, ime, priimek, email, izob, izk, prib, opis) ";
$sql = $sql . "VALUES(".$username.", ".$ime.", ".$priimek$.", ".$email.", ".$izob.", ".$izk.", ".$prib.", ".$opis.")";

remove username to your values and add backticks to insert .

it should be like this:

$sql = "INSERT INTO profil (`ime`, `priimek`, `email`, `izob`, `izk`, ``prib, `opis`) VALUES(`ime` , `priimek ` , `email` , `izob` , `izk` , `prib` , `opis`)";

Hey guys thnx for help i found soulution. this line was wrong:

$sql= "INSERT INTO test (`column`) VALUES(  '$value1' '$value2)";

Tnx guys

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM