I have two registration form for users one of them requires more fields to enter data.
My first question is about how to make tables? I think I should make one table because for loging I should connect to one table only
But in this way how should I insert data from the form which has less fields?
I wrote this code:
$id='';
$password = md5($password);
$data = array(':id'=>$id,':password'=>$password,':mobile'=>$mobile, ':email'=>$email);
$stmt = $con->prepare('INSERT INTO users VALUES(:id,:password, :mobile, :email ) ');
$stmt->execute($data);
and it makes an error because there are some other columns in the table like $firstname, $lastname etc. So what should I do?
One way is that I write:
$firstname= '';
$lastname = '';
in this way I insert empty data but is it the correct way?
You should always explicitly name the columns you're working with in all operations, never simply rely on their implicit "order". For INSERT queries, the syntax is:
INSERT INTO users (id, password, mobile, email)
VALUES (:id, :password, :mobile, :email);
Related
I am fairly inexperienced with php and sql and I am having an issue with php variables in the insert into SQL statement.
I have a SQL Table :
CREATE TABLE users (
userID INT PRIMARY KEY,
username VARCHAR(256),
password VARCHAR(256)
);
This isn't the way I made the table as it was made in phpmyadmin but that is exactly how it is
the PHP is so , there is validation code aswell but it is not necessary:
$userUsername = $_POST["username"];
$userPassword = $_POST["password"];
$sqlinsert = "INSERT INTO users(username,password) VALUES ('$userUsername','$userPassword');";
$insertquery = mysqli_query($conn,$sqlinsert)
or die ("Problem with insert query");
Either you need to assign auto increment to primary key (userID).
Or you have to pass value for it like
$sqlinsert = "INSERT INTO users(userID, username, password) VALUES (1, '$userUsername', '$userPassword');";
if you have Auto Increment in ID then leave a blank first
$sqlinsert = "INSERT INTO users(userID,username,password)
VALUES ('','$userUsername','$userPassword')";
Or fill it with ID if not Auto Increment.
$sqlinsert = "INSERT INTO users(userID,username,password)
VALUES ('1','$userUsername','$userPassword')";
And as already mentioned in comments of your post your code is vulnerable to SQL Injection.
can use PDO Prepare Statement,too not necessarily ofcourse
I am designing a website with user login and registration with email verification, and when the user registers an account, it will successfully, and correctly, insert the user record into the database in the "users" table.
But when I try to pull the users id that is created when inserted to insert them into a second table for a roster of all members of the site (this is for a gaming clan), it inserts the user id as 0 in the roster table, regardless of what their id is on the "users" table for that user.
heres my code:
if($insert_stmt = $db->prepare("INSERT INTO users (username, password, email, date, actcode) VALUES (?, ?, ?, ?, ?)"))
{
$insert_stmt->bind_param('sssss', $username, $password, $email, $date, $actcode);
$stmt = $db->prepare("SELECT id FROM users WHERE email = ?");
if($stmt)
{
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->fetch();
$stmt->store_result();
$stmt->bind_result($ui);
}
$stmt = $db->prepare("INSERT INTO roster (userid, joindate) VALUES (?, ?)");
if($stmt)
{
$stmt->bind_param('ss', $ui, $date);
$stmt->execute();
}
if(!$insert_stmt->execute()) {
header('Location: error.php?err=Registration failure: INSERT');
}
}
for security reasons I have left certain variables and sections of the code omitted that do not have any bearing on this section causing me a headache.
I can't figure out why it is not inserting the newly creating "id" from "users" for that user account into the "roster" table under the "userid" column.
Also, just to test something, I also went and set a session variable
$_SESSION['uid'] = $ui;
directly after the line
$stmt->store_result($ui);
and echoed it on my index.php file, and it shows the session variable as 0 as well.
You could simply use this function: mysqli::$insert_id instead of writing your second query.
Replace this line:
$stmt = $db->prepare("SELECT id FROM users WHERE email = ?");
With:
$userid = $db->insert_id;
Let me know if this works.
Still wasn't able to get it to work with the the solutions provided, but decided to just merge everything into the users table, which fixed the issue. As far as checking if it is executing, I am putting in some checks to make sure it goes through. Thanks for the help and advise.
i am having a problem with inserting records to my tables as i want to insert values into specific columns if only the value is not null, my query goes like this
i have tried:
INSERT INTO users(id,name,phone,address) VALUES($userId,$userName,$userPhone,$userAddress);
but it gives me error if on client side one of the parameters is not sent not all the time the client side send all the parameters (id,name,phone,address) i want to have some kind of condition instead of the handle all combinations to the query to go over this problem
You should be using prepared queries, but your immediate problem is that you aren't quoting anything:
$query = "INSERT INTO users(id,name,phone,address) VALUES('$userId', '$userName', '$userPhone', '$userAddress')";
Now, assuming you're doing this properly using a PDO connection, this is how you should be doing it to protect your database:
$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$query = "INSERT INTO users (id, name, phone, address) VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query);
$result = $stmt->execute(array($userId,$userName,$userPhone,$userAddress));
if ($result) {
//success
} else {
//failure
}
Put ' inside VALUES () like '$userId'.
INSERT INTO users(id,name,phone,address) VALUES('$userId','$userName','$userPhone','$userAddress');
If parameter are not coming, then let it Insert Null in DB Table column. (Allow Null). And, if you don't want to insert NULL in DB Table column, then assign any default value before inserting.
So I'm doing a register page for teams. So the user who creates a team will be inserted into a database table called alcs_teams. That's not the problem. Then I'd like to insert them into another table called alcs_member_teams. That keeps track of the members on each team.
So I do an insert query into the alcs_teams which works fine. Then I try to select the team id from the data that was just inserted a few lines below. Does this work? I can't get it to work, it just puts 0 in that field in the database.
$member = mysql_query("Select * from members where id=$_SESSION[tid]");
$member = mysql_fetch_array($member);
mysql_query("INSERT into alcs_team (teamid, name, leader, email) VALUES('', $_POST[name]', '$member[name]','$member[email]')");
$teamid = ("Select * from alcs_team where leader=$member[name]");
$row = mysql_fetch_array($teamid);
mysql_query("INSERT into alcs_member_teams (id, alcs_teamid, alcs_memberid, member_name) VALUES ('', '".$row[teamid]."' , '".$member[id]."', '".$member[name]."')");
You should look into using parametrized queries whenever possible
Example:
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$params = array($name, $email);
$sql = 'INSERT INTO CustomerTable (Name, Email) VALUES (?, ?)';
$stmt = sqlsrv_query($conn, $tsql, $params);
This prevents SQL Injection, which can cause a lot of trouble on your site.
i used this code
<?php
$conn = new PDO("mysql:host=localhost;dbname=CU4726629",'CU4726629','CU4726629');
$sql="INSERT INTO review (username, movie_name, ratings) VALUES ("$_POST['username']","$_POST['moviename']","$_POST['ratings']")";
header('Location: reviews.php');
?>
but it keeps giving me this error
Parse error: syntax error, unexpected T_VARIABLE in
/home/4726629/public_html/check_login.php on line 5
Take this for an example:
<?php
// insert some data using a prepared statement
$stmt = $dbh->prepare("insert into test (name, value) values (:name, :value)");
// bind php variables to the named placeholders in the query
// they are both strings that will not be more than 64 chars long
$stmt->bindParam(':name', $name, PDO_PARAM_STR, 64);
$stmt->bindParam(':value', $value, PDO_PARAM_STR, 64);
// insert a record
$name = 'Foo';
$value = 'Bar';
$stmt->execute();
// and another
$name = 'Fu';
$value = 'Ba';
$stmt->execute();
// more if you like, but we're done
$stmt = null;
?>
You just wrote a string in your above code:
$sql="INSERT INTO review (username, movie_name, ratings) VALUES ("$_POST['username']","$_POST['moviename']","$_POST['ratings']")";
Above answers are correct, you will need to concat the strings to form a valid sql query. you can echo your $sql variable to check what is to be executed and if is valid sql query or not. you might want to look in to escaping variables you will be using in your sql queries else your app will be vulnerable to sql injections attacks.
look in to
http://php.net/manual/en/pdo.quote.php
http://www.php.net/manual/en/pdo.prepare.php
Also you will need to query you prepared sql statement.
look in to http://www.php.net/manual/en/pdo.query.php
A couple of errors:
1) you have to concat the strings!
like this:
$sql="INSERT INTO review (username, movie_name, ratings)
VALUES (".$_POST['username'].",".$_POST['moviename'].",".$_POST['ratings'].")";
2) you are not using the PDO at all:
after you create the "insert" string you must query the db itself, something like using
$conn->query($sql);
nb: it is pseudocode
3) the main problem is that this approach is wrong.
constructing the queries in this way lead to many security problems.
Eg: what if I put "moviename" as "; drop table review;" ??? It will destroy your db.
So my advice is to use prepared statement:
$sql="INSERT INTO review (username, movie_name, ratings)
VALUES (?,?,?)";
$q = $conn->prepare($sql);
$fill_array = array($_POST['username'], $_POST['moviename'], $_POST['ratings']);
$q->execute($fill_array);
You forgot dots:
$sql="INSERT INTO review (username, movie_name, ratings)
VALUES (".$_POST['username'].",".$_POST['moviename'].",".$_POST['ratings'].")";
and fot the future for now your variables are not escaped so code is not secure
String in a SQL-Statment need ', only integer or float don't need this.
$sql="INSERT INTO review (username, movie_name, ratings) VALUES ('".$_POST['username']."','".$_POST['moviename']."','".$_POST['ratings']."')";