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
Related
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.
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
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'm currently experiencing some problems.
Basically, I use PDO and I want to create a table and insert some stuff into the table.
I've tried searching for solutions, but it doesn't seem like anything is working.
Please take a look at this:
public function install()
{
global $con;
$sql = "CREATE TABLE if not exists users
(id INT(11) PRIMARY_KEY,
uname VARCHAR(30) ,
pass VARCHAR (40))";
$sq = $con->query($sql);
if ($sq)
{
echo "Table successfully created!";
}
else
{
$this->errors[] = 'Error creating table: users';
}
$sql_code = "INSERT INTO users (
`uname`,
`pass` ) VALUES(
`$this->username`,
`$this->password`
)";
$sq1 = $con->query($sql_code);
if ($sql_code)
{
echo "Successfull!";
}
else
{
echo "Error creating admin user!";
}
}
NOTE: The database connection is set in another file called config.php and I've also included the config.php file to the code.
Well, there could be plenty of things going on, perhaps at the same time.
Maybe your database connection is failing (I'd recommend passing the connection $con by reference to the function install rather than using the global keyword).
Maybe you don't have enough rights to create a table in the database.
Also you are not binding your parameters, this would be the correct way to do it:
$sql_code = "
INSERT INTO users (
uname,
pass
)
VALUES (
:userName,
:password
);
";
$sq1 = $con->prepare($sql_code);
$sq1->bindParam(':userName', $userName);
$sq1->bindParam(':password', $password);
$sq1->query($sql_code);
I'm trying to set up a simple database with Heroku/PGSQL. So far I've made a connection and created the table I want, but whenever I try and insert data to the table nothing happens.
For testing purposes, I'm using the code
$dbconn = pg_connect(pg_connection_string());
if (!$dbconn) {
echo "Database connection error. ";
}
else {
// Create table
$create="CREATE TABLE IF NOT EXISTS users (
id INT PRIMARY KEY NOT NULL,
gender CHAR(30),
age INT,
location CHAR(30),
timestamp CHAR(30)
)";
// Execute query
if (pg_query($dbconn,$create)) {
echo "Table users created successfully. ";
}
else {
echo "Error creating table. ";
}
}
function insert() {
$dbconn = pg_connect(pg_connection_string());
if (!$dbconn) {
echo "Database connection error 2. ";
}
else {
# Insert query
$insert = "INSERT INTO users (id, gender, age, location, timestamp) VALUE (1234, 'male', 99, 'UK', '31/05/2013')";
# Execute query
if (pg_query($dbconn,$insert)) {
echo "Data entered successfully. ";
}
else {
echo "Data entry unsuccessful. ";
}
}
}
When run, it returns "Table users created successfully." However, when I call the $$insert$$ function (I will later use this to insert different values into the table) it always returns unsuccessful.
What am I doing wrong?
$insert = "INSERT INTO users (id, gender, age, location, timestamp)
VALUES (1234, 'male', 99, 'UK', '31/05/2013')";
maybe you shouldn't use char for timestamp
In the insert statement, VALUE should be VALUES.
Anyway, you should try to recover the error message given by database. I think it's possible in PHP. You'll have much more information about the reason of your error.