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
Related
im a newbie in php and im facing this problem...i get with it 3 days and im going mad... ;). Im trying to implement a table with users of a web application. So i have to check that the user doesnt exist.
My sql table:
DROP TABLE users;
CREATE TABLE users (
idUser INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
mail VARCHAR(45) NOT NULL UNIQUE,
name VARCHAR(45) NOT NULL,
password VARCHAR(255) NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
role enum ("admin", "user"),
state BOOLEAN,
forgotpass VARCHAR(32) NOT NULL
);
Also this code works ( test if the user already exists in the table):
//$query="SELECT mail FROM proba.users WHERE mail='{$correu}'";
$sql = 'SELECT * FROM users WHERE mail = :mailparam';
//$sql = 'SELECT * FROM users';
$stmt = $con->prepare($sql);
// 2. execute to insert a row
// with an associative array
$stmt->execute(
array(':mailparam'=>$correuFormulari)
);
// 3. get all rows
$rows = $stmt->fetchAll();
foreach ($rows as $rowActual) {
echo $rowActual['mail'] . "<br>";
echo $rowActual['password'] . "<br>";
}
But following the same logic i cant insert an element:
if(count($rows) > 0){
echo "L'usuari ja existeix";
echo "<p><a href='registreUsuari.php'>Torna</a></p>";
} else{
echo "Usuari no trobat. Passem a insertar";
//INSERT INTO users (mail, password, role, name, created_at,forgotpass) VALUES ("p#gmail.com", "pepe","user", "pepito", current_Time,"forgotpass");
$user="admin";
$sqlinsert = 'INSERT INTO users (mail, password, role, name,forgotpass) VALUES (:mail, :passwordform,:usuari, :nomFormulari,:forgotpass)';
//$sql = 'SELECT * FROM users';
$stmtinsertar = $con->prepare($sqlinsert);
// $stmt = $con->prepare("INSERT INTO users (mail, password, role, name, created_at,forgotpass) VALUES (:mail, :password,:user, :nomFormulari, :data,:forgotpass)");
/* $stmtinsertar->bindParam(':mail', $correuFormulari);
$stmtinsertar->bindParam(':password', $passwordFormulari);
$stmtinsertar->bindParam(':user', $user);
$stmtinsertar->bindParam(':nomFormulari', $nomFormulari);
//$stmt->bindParam(':data', $data);
$stmtinsertar->bindParam(':forgotpass', "forgotpass");
INSERT INTO users (mail, password, role, name,forgotpass) VALUES ("hola#g,aoƱ", "pepe","user", "pedro","forgot")
*/
try
{
//$stmtinsertar->execute();
$stmt->execute(
array(':mail'=> "$correuFormulari",
':passwordform'=> "$passwordFormulari",
':usuari'=> "$user",
':nomFormulari'=> "$nomFormulari",
':forgotpass'=> "forgotpass")
);
}
catch(PDOException $e)
{
handle_sql_errors($selectQuery, $e->getMessage());
}
echo "S'ha creat l'usuari";
//header('Location: '.'login.php');
// $stmt->close();
}
I enter in the correct if, but i cant insert into the table....
The error shows something like:
pepekjjp#gamil.comConexio : object(PDO)#2 (0) { } hoola0Usuari no trobat. Passem a insertar
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
As you can read in the code i also tried to use bind->Params....
Any help would be apreciated.
Also would like to know, which form of executing PDO is preferred, using bindParameter or using an array.
Thanks in advance
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 2 years ago.
I am trying to update an entry in a database when a user edits their information, but when I tested it, it threw an error for trying to use a bind_param statement with a WHERE clause (as there might not be any such instance). My code passes in the User ID of the current user to be used in the WHERE clause, so no matter what, there will always be an instance of that User ID, but the system refuses to recognize that. My code is below:
if(preg_match("#^[a-zA-Z0-9\d._-]+$#", $userpassword)) {
$sql = "SELECT * FROM User WHERE (Email = '$email' and UserID != '$userid')";
$res = $mysqli->query($sql);
if ($res->num_rows > 0) {
$row = $res->fetch_assoc();
echo "<script type='text/javascript'>
alert('This email is already in use. For security purposes, you have been signed out.');
window.location.href = '../volunteer.html';
</script>";
} else {
$sql = "SELECT * FROM User WHERE (UserID = '$userid')";
$res = $mysqli->query($sql);
if ($res->num_rows > 0) {
$stmt = $mysqli->prepare("UPDATE User SET FirstName, LastName, Email, Phone, UserPassword WHERE UserID = '$userid' VALUES (?,?,?,?,?)");
$stmt->bind_param("sssss", $firstname, $lastname, $email, $phone, $userpassword);
echo $stmt;
$stmt->execute();
echo "<script type='text/javascript'>
alert('The changes were successfully saved. For security purposes, you have been signed out.');
window.location.href = '../volunteer.html';
</script>";
}
}
as well as the database the information is stored in:
CREATE DATABASE IF NOT EXISTS VOLUNTEER_HOURS;
USE VOLUNTEER_HOURS;
DROP TABLE IF EXISTS ACTIVITY;
DROP TABLE IF EXISTS USER;
CREATE TABLE IF NOT EXISTS USER(
UserID int NOT NULL AUTO_INCREMENT,
FirstName varchar(30) NOT NULL,
LastName varchar(30) NOT NULL,
Email varchar(30) NOT NULL,
Phone bigint NOT NULL,
UserPassword varchar(30) NOT NULL,
PRIMARY KEY (UserID)
) ENGINE = INNODB;
CREATE TABLE IF NOT EXISTS ACTIVITY(
ActivityID int NOT NULL AUTO_INCREMENT PRIMARY KEY,
ActivityType varchar(50) NOT NULL,
ActivityDate date NOT NULL,
Length double NOT NULL,
UserID int,
FOREIGN KEY (UserID) REFERENCES USER(UserID)
) ENGINE = INNODB;
How can I use the WHERE clause to edit the record of the current user without throwing this error?
The syntax for UPDATE is
UPDATE <table name>
SET <1st column name> = <1st value>
...
<1st column name> = <1st value>
WHERE <conditions>;
A VALUES clause is typically used in INSERT statements. You seem to confuse them.
So change
$stmt = $mysqli->prepare("UPDATE User SET FirstName, LastName, Email, Phone, UserPassword WHERE UserID = '$userid' VALUES (?,?,?,?,?)");
to
$stmt = $mysqli->prepare("UPDATE User SET FirstName = ?, LastName = ?, Email =?, Phone = ?, UserPassword = ? WHERE UserID = ?");
Note that you also should parameterize the user ID and all the other values in the other queries.
Check for errors. Like that you would have gotten a message, that indicated that $mysqli->prepare() failed and why.
If the password is stored as clear text: Don't do that. Only store the salted hash of a password.
This query change only the name, I want change the username too...
<?php
define('HOST', 'localhost');
define('USERNAME', 'root');
define('PASSWORD', '');
define('DATABASE', 'mydb');
$mysqli = new mysqli(HOST, USERNAME, PASSWORD, DATABASE);
$query = "CREATE TABLE users (id INT UNSIGNED NOT NULL AUTO_INCREMENT, username VARCHAR(50) NOT NULL, name VARCHAR(50) NULL, PRIMARY KEY (id), UNIQUE(username)) ENGINE = MyISAM";
if ($mysqli->query($query)) {
$query = "INSERT INTO users (id, username, name) VALUES (1, 'user1', 'name1')";
if ($mysqli->query($query)) {
$query = "UPDATE users SET username = 'user_1', name = 'name_1' WHERE id = 1";
if ($mysqli->query($query)) {
$query = "SELECT id, username, name FROM users WHERE id = 1";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo 'id = ' . $row['id'] . ', username = ' . $row['username'] . ', name = ' . $row['name'];
}
$result->free();
}
}
}
$mysqli->close();
?>
In this example:
Started as [1, user1, name1]
Changed to [1, user1, name_1]
Instead of [1, user_1, name_1]
There is no way to update UNIQUE columns?
Your script won't run (table creation) when reloading it (only on the first/initial execution), since your table already exists and MySQL is failing on you silently, since you're not checking for errors.
Sidenote: You may have slightly modified your script and then ran it after.
Having included the following debugging code at the top of your script, you would have been thrown errors about it and is crucial when debugging during development before going live:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// rest of your code
Therefore, you can only run that script once. You need to either test it again with a new table name, or remove the table creation code.
You can also check if the table exists.
References:
http://dev.mysql.com/doc/refman/5.7/en/create-table.html
https://dev.mysql.com/doc/refman/5.5/en/replication-features-create-if-not-exists.html
A quick example:
CREATE TABLE IF NOT EXISTS `test`
You can also use UPDATE IGNORE table ... syntax (not to be used with your present table creation codes though):
http://dev.mysql.com/doc/refman/5.7/en/update.html
and INSERT IGNORE INTO table
https://dev.mysql.com/doc/refman/5.5/en/insert.html
Now your entire code (as a rewrite) would look like this:
$query = "CREATE TABLE IF NOT EXISTS users
(id INT UNSIGNED NOT NULL AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
name VARCHAR(50) NULL,
PRIMARY KEY (id),
UNIQUE(username))
ENGINE = MyISAM";
if ($mysqli->query($query)) {
$query = "INSERT IGNORE INTO users (id, username, name) VALUES (1, 'user1', 'name1')";
if ($mysqli->query($query)) {
$query = "UPDATE IGNORE users SET username = 'user_1', name = 'name_1' WHERE id = 1";
if ($mysqli->query($query)) {
$query = "SELECT id, username, name FROM users WHERE id = 1";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo 'id = ' . $row['id'] . ', username = ' . $row['username'] . ', name = ' . $row['name'];
}
$result->free();
}
}
}
There is no way to update UNIQUE columns?
Yes, with UPDATE IGNORE table ....
http://dev.mysql.com/doc/refman/5.7/en/update.html
However and with your present code, it will fail on the INSERT, since that is being executed before the UPDATE.
Think logically and you will see what is going on here.
I'm setting up a simple website where each user gets their own table (bad idea, I know), in which other users can put comments into - like a super budget version of a Facebook-wall.
This is what my query looks like when I create the table:
$userTable = mysqli_query($conn, "CREATE TABLE `".$epost."`(
ID INT(255) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
eMail VARCHAR(50) NOT NULL,
comment VARCHAR(500) NOT NULL,
timestampp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)");
However, when I try to take the values from a form, and insert them into the specific table they can't seem to find their way in there. Here's my code of that:
<?php
include 'connect.php';
/*if(isset ($_POST['userUser']))*/
$valueEmail = mysqli_real_escape_string($conn, $_POST['userEmail']);
$valueUser = mysqli_real_escape_string($conn, $_POST['userUser']); /*have the user to input the name, so i can connect to the correct DB*/
$valueMessage = mysqli_real_escape_string($conn, $_POST['userMessage']);
$findUserTable = "SELECT * FROM UserInfo WHERE Firstname = '$valueUser'";
$findUserEmail = mysqli_query($conn, $findUserTable);
if(mysqli_num_rows($findUserEmail) > 0) /*finding the name of the persons email*/
{
while ($result = mysqli_fetch_assoc($findUserEmail))
{
$email = $result['Email'];
}
}
/* VALIDATION HERE */
$sql = "INSERT INTO ".$email." (eMail, comment) VALUES ('$valueEmail', '$valueMessage')"; /* wrong query?*/
header("refresh:10 url=userProfil.php");
/*echo '<script>alert("Meddelande skapat!");</script>';*/
echo $sql;
mysqli_close($conn);
?>
I've been trying different 'versions' of the variable, like ".$email.", '.$email.' and ".$epost.". I get the correct name when i echo out my query or just the variable - but it can't seem to find the table?
I'm very aware that my code smells badly, so please spare me on that point.
You just simple write your query forget to execute it.
$sql = "INSERT INTO ".$email." (eMail, comment) VALUES ('$valueEmail', '$valueMessage')"; /* wrong query?*/
Use this
mysqli_query($conn,$sql);//for execute
Better use Bind and prepare statement as
$sql = "INSERT INTO ".$email." (eMail, comment) VALUES (? ,?)"; /* wrong query?*/
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $valueEmail, $valueMessage);
/* Execute the statement */
$stmt->execute();
$row = $stmt->affected_rows;
if ($row > 0) {
echo "data inserted";
} else {
"error";
}
Read http://php.net/manual/en/mysqli-stmt.bind-param.php
I have kind of a "problem" that I do not know how it happened. If I add rows to my table via php it just adds them randomly somewhere. But I want them to be added on top. Instead it justs add them all over the table.
$name = ($_GET["name"]);
$sql = "INSERT INTO $DB_Table VALUES('$name')";
$number = ($_GET["number"]);
$sql = "INSERT INTO $DB_Table VALUES('$number')";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die (mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
mysql_query("INSERT INTO $DB_Table (Name,number)
VALUES ('$name','$m_yolo')");
$res = mysql_query($sql,$con) or die(mysql_error());
mysql_close($con);
if ($res) {
echo "success";
}else{
echo "faild";
}// end else
?>
There is no such thing as row ordering in a relational table. If you want them ordered, you need to use an ORDER BY clause. You can add a TIMESTAMP column, which you can sort on when you select your data: 11.3.1. The DATE, DATETIME, and TIMESTAMP Types
Create another table but add an ID auto-increment column in it:
CREATE TABLE IF NOT EXISTS `table` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`number` int(10) NOT NULL,
PRIMARY KEY (`id`)
);
Then you can insert new rows like this:
$sql = "INSERT INTO $DB_Table (id, name,number) VALUES ('', '$name', '$number')";
Your new entries will be sorted by id then. You can order them in you select query with:
$sql = "SELECT 'name', 'number' FROM `table` ORDER BY 'id' DESC";
One remark about your code though: it is not safe to directly use the values from $_GET as you do at the beginning of your code. Try using mysql_real_escape_string() for example.