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
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 is my code, we have database called "our_new_database".
The connection is fine, as well as the HTML Form and credentials and I still cannot insert information into the database.
Table is created, I can see the columns and lines in XAMPP / phpMyAdmin.
The only error I'm getting is the last echo of the If/Else Statement - "Could not register".
Tried everything I can and still cannot make this insertion to work normally.
Can someone advise me something?
<?php
include "app".DIRECTORY_SEPARATOR."config.php";
include "app".DIRECTORY_SEPARATOR."db-connection.php";
include "app".DIRECTORY_SEPARATOR."form.php";
$foo_connection = db_connect($host, $user_name, $user_password, $dbname);
$sql = "CREATE TABLE user_info(
user_name_one VARCHAR(30) NOT NULL,
user_name_two VARCHAR(30) NOT NULL,
user_email VARCHAR(70) NOT NULL UNIQUE
)";
if(mysqli_query($foo_connection, $sql)){
echo "Table created successfully";
}
else {
echo "Error creating table - table already exist.".mysqli_connect_error($foo_connection);
}
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$user_name_one = $_POST["userOne"];
$user_name_two = $_POST["userTwo"];
$user_email = $_POST["userEmail"];
$sql = "INSERT INTO user_info (userOne,userTwo,userEmail) VALUES('".$_POST['userOne']."',('".$_POST['userTwo']."',('".$_POST['userEmail']."')";
if(mysqli_query($foo_connection,$sql))
{
echo "Successfully Registered";
}
else
{
echo "Could not register";
}
}
$foo_connection->close();
You should avoid the direct use of variables in SQL statements, instead, you should use parameterized queries.
This also should avoid the need to string concatenation and manipulation problems.
$stmt = $foo_connection->prepare("INSERT INTO user_info
(user_name_one,user_name_two,user_email))
VALUES(?,?,?)");
$stmt->bind_param('sss', $user_name_one, $user_name_two, $user_email );
$stmt->execute();
You need to change
$sql = "INSERT INTO user_info (userOne,userTwo,userEmail) VALUES('".$_POST['userOne']."',('".$_POST['userTwo']."',('".$_POST['userEmail']."')";
To
$sql = "INSERT INTO `user_info`(`user_name_one`,`user_name_two`,`user_emai`l) VALUES ('$user_name_one','$user_name_two','$user_email')";
remember you should use prepared query
$sql= $foo_connection->prepare("INSERT INTO user_info
(user_name_one,user_name_two,user_email))
VALUES(?,?,?)");
$sql->bind_param('sss', $user_name_one, $user_name_two, $user_email );
$sql->execute();
$sql = "INSERT INTO user_info (userOne,userTwo,userEmail) VALUES('".$_POST['userOne']."','".$_POST['userTwo']."','".$_POST['userEmail']."')";
I reckon your parentheses on this line:
$sql = "INSERT INTO user_info (userOne,userTwo,userEmail) VALUES('".$_POST['userOne']."',('".$_POST['userTwo']."',('".$_POST['userEmail']."')";
Do not match, it should look like something like this:
$sql = "INSERT INTO user_info (userOne,userTwo,userEmail) VALUES('".$_POST['userOne']."','".$_POST['userTwo']."','".$_POST['userEmail']."')";
Cause for know your query is:
"INSERT INTO user_info (userOne,userTwo,userEmail) VALUES('value',('value1',('value2')"
As said above you might use:
echo $foo_connection->error
To see some errors displayed
I create some table(in MySQL):
create table clients
( clientid int unsigned not null auto_increment primary key,
Name char(50) not null,
SecondName char(50) not null,
address char(100) not null,
City char(30) not null
Email char(100);
I want to input datas(Name,SecondName,address,City,Email) into my database NewClientBase from webpage by filling by customer his personal data, but clientid should be generated by program:
<html>
<?php
...
// short names initialization. Taken from filling external form
$Name=$_POST['Name'];
$SecondName=$_POST['SecondName'];
$Address=$_POST['Address'];
$City=$_POST['City'];
$Email=$_POST['Email'];
$clientid=0;
if (!$Name || !$SecondName || !$Address || !$City || !$Email) {
echo "Not all data completed.<br />"
."Return and try again";
exit;
}
if (!get_magic_quotes_gpc()) {
$Name = addslashes($Name);
$SecondName = addslashes($SecondName);
$Address = addslashes($Address);
$City = addslashes($City);
$Email = doubleval($Email);
}
# $db = new mysqli('localhost', 'root', '********', 'NewClientBase');
$wynik_sprawdzania= mysqli_query($db, $sprawdzanie);
$ile_znalezionych=$wynik_sprawdzania->fetch_row();
$ilosc_pol=$wynik_sprawdzania->field_count;
.....
// a new record with the next number is calculated:
$clientid=$wynik_sprawdzania->fetch_row()+1;
....
and created a new record with this number:
$zapytanie = "insert into clients values ('".$clientid."','".$Name."','".$SecondName."', '".$Address."','".$City."', '".$Email."')";
$wynik = $db->query($zapytanie);
.....
$db->close();
?>
</html>
the problem is:
if (for example) 5th record is generated and input into database like this
$zapytanie = "insert into clients values (5,'".$Name."','".$SecondName."', '".$Address."','".$City."', '".$Email."')";
$wynik = $db->query($zapytanie);
all record is inserted into database correctly.
but if it is inserted like this
$zapytanie = "insert into clients values
('".$clientid."','".$Name."','".$SecondName."', '".$Address."','".$City."', '".$Email."')";
$wynik = $db->query($zapytanie);
($clientid No 5 is calculated programly as shown above) record is not created. Neither '".clientid."' nor '.$clientid.' Can anybody help me? Any solution exists? Thanks
ClientId is defined as Int, not as string. You try to input string. Remove the single quotes on $clientid.
$zapytanie = "insert into clients values
(".$clientid.",'".$Name."','".$SecondName."', '".$Address."','".$City."', '".$Email."')";
$wynik = $db->query($zapytanie);
The variable $clientid should be considered as integer and should not add any quotes.
$zapytanie = "insert into clients values
(".$clientid.",'".$Name."','".$SecondName."', '".$Address."','".$City."', '".$Email."')";
$wynik = $db->query($zapytanie);
Hope this helps
I am trying to enter into a table in with PDO if using an if condition. My code for the function is below:
function add_user_info($conn, $user, $info, $fName, $sName, $past, $pos){
// Prepare and execute statements
$info1 = addslashes($info);
$sql = $conn->prepare("SELECT * FROM `User_Info` WHERE `User` = '$user'");
$sql->execute();
if ($sql->fetch()){
// Update current entry
$sql1 = $conn->prepare("UPDATE `User_Info` SET `Info` = '$info1' AND `Past` = '$past' AND `Position` = '$pos' WHERE `User` = '$user'");
} else {
// Create new entry
$sql1 = $conn->prepare("INSERT INTO `User_Info` (`User`, `Info`, `FName`, `SName`, `Past`, `Position`) VALUES ('$user', '$info1', '$fName', '$sName', '$past', '$pos')");
}
$sql1->execute();
}
The ONLY (I repeat, ONLY) part that is not working for me is on line 9 with the update query. I have narrowed the problem down to it being related with the update of the Info column, and not only that but it is a problem with the string so the variable $info1.
I am trying to pass in a string of text from CKEditor. It is a rich text string and so has HTML tags, quotations, etc in it when passed to the SQL.
The initial creation of the row in the table (line 12 of the function) works PERFECTLY so it is only on the update that the string is seen as funny. When I update with a word in place of $info1 it still does not work.
As shown in phpmyadmin, my table schema is as follows:
Update command multiple set is separated by , not and
UPDATE `User_Info`
SET
`Info` = '$info1' ,
`Past` = '$past' ,
`Position` = '$pos'
WHERE `User` = '$user'"
Change AND to ,
$sql1 = $conn->prepare("UPDATE `User_Info` SET `Info`='$info1', `Past`='$past', `Position`='$pos' WHERE `User`='$user'");
I have this code to select all the fields from the 'jobseeker' table and with it it's supposed to update the 'user' table by setting the userType to 'admin' where the userID = $userID (this userID is of a user in my database). The statement is then supposed to INSERT these values form the 'jobseeker' table into the 'admin' table and then delete that user from the 'jobseeker table. The sql tables are fine and my statements are changing the userType to admin and taking the user from the 'jobseeker' table...however, when I go into the database (via phpmyadmin) the admin has been added by none of the details have. Please can anyone shed any light onto this to why the $userData is not passing the user's details from 'jobseeker' table and inserting them into 'admin' table?
Here is the code:
<?php
include ('../database_conn.php');
$userID = $_GET['userID'];
$query = "SELECT * FROM jobseeker WHERE userID = '$userID'";
$result = mysql_query($query);
$userData = mysql_fetch_array ($result, MYSQL_ASSOC);
$forename = $userData ['forename'];
$surname = $userData ['surname'];
$salt = $userData ['salt'];
$password = $userData ['password'];
$profilePicture = $userData ['profilePicture'];
$sQuery = "UPDATE user SET userType = 'admin' WHERE userID = '$userID'";
$rQuery = "INSERT INTO admin (userID, forename, surname, salt, password, profilePicture) VALUES ('$userID', '$forename', '$surname', '$salt', '$password', '$profilePicture')";
$pQuery = "DELETE FROM jobseeker WHERE userID = '$userID'";
mysql_query($sQuery) or die (mysql_error());
$queryresult = mysql_query($sQuery) or die(mysql_error());
mysql_query($rQuery) or die (mysql_error());
$queryresult = mysql_query($rQuery) or die(mysql_error());
mysql_query($pQuery) or die (mysql_error());
$queryresult = mysql_query($pQuery) or die(mysql_error());
mysql_close($conn);
header ('location: http://www.numyspace.co.uk/~unn_v002018/webCaseProject/index.php');
?>
Firstly, never use SELECT * in some code: it will bite you (or whoever has to maintain this application) if the table structure changes (never say never).
You could consider using an INSERT that takes its values from a SELECT directly:
"INSERT INTO admin(userID, forename, ..., `password`, ...)
SELECT userID, forename, ..., `password`, ...
FROM jobseeker WHERE userID = ..."
You don't have to go via PHP to do this.
(Apologies for using an example above that relied on mysql_real_escape_string in an earlier version of this answer. Using mysql_real_escape_string is not a good idea, although it's probably marginally better than putting the parameter directly into the query string.)
I'm not sure which MySQL engine you're using, but your should consider doing those statements within a single transaction too (you would need InnoDB instead of MyISAM).
In addition, I would suggest using mysqli and prepared statements to be able to bind parameters: this is a much cleaner way not to have to escape the input values (so as to avoid SQL injection attacks).
EDIT 2:
(You might want to turn off the magic quotes if they're on.)
$userID = $_GET['userID'];
// Put the right connection parameters
$mysqli = new mysqli("localhost", "user", "password", "db");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Use InnoDB for your MySQL DB for this, not MyISAM.
$mysqli->autocommit(FALSE);
$query = "INSERT INTO admin(`userID`, `forename`, `surname`, `salt`, `password`, `profilePicture`)"
." SELECT `userID`, `forename`, `surname`, `salt`, `password`, `profilePicture` "
." FROM jobseeker WHERE userID=?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param('i', (int) $userID);
$stmt->execute();
$stmt->close();
} else {
die($mysqli->error);
}
$query = "UPDATE user SET userType = 'admin' WHERE userID=?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param('i', (int) $userID);
$stmt->execute();
$stmt->close();
} else {
die($mysqli->error);
}
$query = "DELETE FROM jobseeker WHERE userID=?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param('i', (int) $userID);
$stmt->execute();
$stmt->close();
} else {
die($mysqli->error);
}
$mysqli->commit();
$mysqli->close();
EDIT 3: I hadn't realised your userID was an int (but that's probably what it is since you've said it's auto-incremented in a comment): cast it to an int and/or don't use it as a string (i.e. with quotes) in WHERE userID = '$userID' (but again, don't ever insert your variable directly in a query, whether read from the DB or a request parameter).
There's nothing obviously wrong with your code (apart from it being insecure with using non-escaped values directly from $_GET).
I'd suggest you try the following in order to debug:
var_dump $userData to check that the values are as you expect
var_dump $rQuery and copy and paste it into phpMyAdmin to see if your query is not as you expect
If you don't find your problem then please post back your findings along with the structure of the tables you're dealing with