Insert Mysql row with default values - php

I need serious help my my sql statement. First, for some reason the default values for bio and user_image are not inserting. Second, my statement works on and off. Sometimes it inserts, sometimes it doesn't. I need some smart person help. Thanks in advance. Heres my code:
$query = "INSERT INTO users VALUES ('{$_POST['display_name']}', '{$_POST['email']}','{$_POST['password']}','active','{$_POST['first_name']}','{$_POST['last_name']}',DEFAULT,DEFAULT)";
mysql_query($query);
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=success.php">';
exit;
Messed up I know, im doing this project to learn more about databases. Heres my db structure:
Field Type Null Default
id int(11) No
username varchar(255) No
email varchar(255) No
password varchar(255) No
status enum('active', 'inactive') No
first_name text No
last_name text No
bio varchar(305) No HEY! theres nothing here yet ....Complete your bio if you want to get rid of this lame placeholder text. Use this space on your page to tell the internet a little bit about yourself. Or just make everyone feel bad by listing all of your amazing accomplishments! I prefer the latter.
user_image varchar(305) No user_profile.jpg
**Changed but still not working:
$query = "INSERT INTO users(username, email, password, first_name,last_name)
VALUES ({$_POST['display_name']}, {$_POST['email']}, {$_POST['password']}, {$_POST['first_name']}, {$_POST['last_name']})";

Your query is fundamentally unsafe - it can be exploited to insert malicious statements, and POOF! your whole database is gone. You really, really need to read this SO thread and use PDO or mysqli instead, or if that's absolutely not an option at the very least use mysql_real_escape_string.
Having said that, since you're not doing any escaping, any string with a ' in it will break your query. Let's say that $_POST['display_name'] is set to Frank's Restaurant. Your query will then start with INSERT INTO users VALUES ('Frank's Restaurant', and MySQL will think that the query stopped erroneously after Frank, since that's followed by a '.
In addition, as Glavić suggested, you need to add a field for the id, or specify fields manually.

Firstly try this:
$query = "INSERT INTO users VALUES ('{$_POST['display_name']}', '{$_POST['email']}','{$_POST['password']}','active','{$_POST['first_name']}','{$_POST['last_name']}',null,null)";
If it wouldn't help try to specify what fields you want to insert. Anyway it is a good practise to do this. Its not very hard, but there are less possibility to get error.
I mean you should try next query:
insert into SomeTable(Field1, Field2, Field5, Field8) values ($field1Data, $field2Data, $field5Data, $field8Data);
Field3, Field4, Field6, Field7 would be default after this.

Related

Syntax Error while inserting students into postgres database via php using nextval

I created a database with my .sql file with this:
CREATE SEQUENCE ec_account_id
start 1
increment 1;
create table ec_account
(id serial PRIMARY KEY,
name VARCHAR(40) not null,
password VARCHAR(80) not null,
email VARCHAR(30) not null,
phone VARCHAR(10) not null);
insert into ec_account values (nextval('ec_account_id'),'admin','68dc71d4b0724561008d7665a37d9f8bba008f95836c0caab9656d9f1983d314','123456#gmail.com','123456789');
insert into ec_account values (nextval('ec_account_id'),'dsds','cfb68d2dba58568ff9e223235ff1b77b3cb42c371403832a434112aabc','johnnsySilva#gmail.com','123456789');
And i could watch it(the table) via terminal. Check the passwords on the html. Everything was going along fine. But now i want to add new persons to the database via an html form and i want the id to increment automatically, however im not being able to insert (via php) the instances on the database cause when i run this code i get this error:
$sql = "INSERT into ec_account values ('nextval('ec_account_id')','$nome','$hashedPass','$email','$telemovel') ";
ERROR: ERROR: syntax error at or near "ec_account_id" LINE 1: INSERT
into ec_account values ('nextval('ec_account_id')','f...
^
Im almost sure it has something to do with the next val but i dont know how to solve it. Can somebody clarify me? I don't want the responsability of having to memorize how many people are already enrolled in the ec_account table, and i thought this was the way to automatically increment the primary key whenever i insert a new row.
Seems like you made a fairly simple mistake:
$sql = "INSERT into ec_account values ('nextval('ec_account_id')','$nome','$hashedPass','$email','$telemovel') ";
Notice your extraneous single quote before nextval. Remove that and the closing one you added and things should be fine.
$sql = "INSERT into ec_account values (nextval('ec_account_id'),'$nome','$hashedPass','$email','$telemovel') ";
Just to clarify, SQL needs quotes around string values. You do not need to randomly add quotes around every variable you are passing.
Another clarification about Postgresql, is that when you define a column as type "serial" Postgresql creates a sequence for you with the name tablename_columname_seq. So you redundantly created a sequence when you could have used nextval('ec_account_id_seq') and do not need to create the sequence ec_account_id.
When you author an insert statement you should avoid using the shorthand method and explicitly list the columns. This avoids issues later should you need to do an insert that doesn't include all columns, or if you add a column to the table which will break your existing insert statements.
Fixed:
$sql = "INSERT into ec_account ('id', 'name', 'password', 'email', 'phone')
values (nextval('ec_account_id'),'$nome','$hashedPass','$email','$telemovel')";
A final word about SQL injections, escaping and parameters:
This technique of using PHP strings to interpolate values is prone to numerous problems and creates vulnerabilities in your system.
I don't know if you are using the pg api or PDO, but in either case, you should be using parameters to send in your values.
Here's a link to the pg_query_params page that explains this.
I'd recommend using PDO personally.

php: how to insert large form data into mysql

I am trying to insert a data from a form which has about 1990 characters into mysql. How ever the insert is not working. when i var_damp the content of the variable is shows the correct content. When i set it to an empty string the insert works. I have done my research and still can't get ti to work. I am not trying to upload a file. This characters are from a textarea in my form.
Below is the insert code:
if (isset($_POST['val'])) {
$score = $_POST['val'];
$course = $_POST['course'];
$mysqli->query("INSERT INTO `evaluate` (`id`, `course`, `score`) VALUES (Null, '$course', '$score')");
Note: is score column has type TEXT in the database.
This is a common problem because most introductions to mysqli don't cover it right away even when it should be the first thing you learn. Inserting into any database, especially SQL, requires carefully escaping the values you're supplying. The way these are escaped varies depending on the platform, but the good news is that mysqli can handle it for you.
The key is using prepared statements:
$stmt = $mysqli->prepare("INSERT INTO evaluate (course, score) VALUES (?,?)");
$stmt->bind_param('ss', $_POST['course'], $_POST['val']);
$stmt->execute();
Now it's best to enable exceptions so that any errors are not ignored. Once in a while we all make little mistakes that can be a giant pain to track down if there isn't any warning about them. Exceptions make a lot of noise.
If you're just getting started with PHP and databases, you might want to evaluate using PDO which is significantly better than mysqli for a number of reasons, or a higher level database layer like Doctrine or
Propel which make using the database a lot more pleasant.
I have a single quote (') in the text and not escaping it meant that the SQL statement was been interpreted wrongly
The correct way to go, and you must always do this, is:
$score = $mysqli->real_escape_string($_POST['val']);
$course = $mysqli->real_escape_string($_POST['course']);
$mysqli->query("INSERT INTOevaluate(id,course,score)VALUES (Null, '$course', '$score')");

Posting MySQL encrypt in PHP

Hi I'm trying to post values from a page into a MySQL DB, however the password field has to be encrypted via the encrypt command.
So far I have this -
$sql="INSERT INTO `ftpuser` (`userid`, `passwd`, `uid`, `gid`, `homedir`, `shell`, `count`, `accessed`, `modified`)
VALUES
('$_POST[userid]', encrypt(".$_POST['passwd']."),'$_POST[uid]','$_POST[gid]','$_POST[homedir]','$_POST[shell]','$_POST[count]','$_POST[accessed]','$_POST[modified]')";
The script connects to the DB fine, however the output is "Error: Unknown column 'test34' in 'field list'"
Thanks.
This statement:
encrypt(".$_POST['passwd'].")
doesn't have any quotes around the value, so mysql gets it as a column name. For example, if your password is test123, this part of query would look like:
encrypt(test123)
while what you really need is
encrypt('test123')
So, you can fix this problem just by adding single quotes
$sql="INSERT INTO `ftpuser` (`userid`, `passwd`, `uid`, `gid`, `homedir`, `shell`, `count`, `accessed`, `modified`)
VALUES
('$_POST[userid]', encrypt('".$_POST['passwd']."'),'$_POST[uid]','$_POST[gid]','$_POST[homedir]','$_POST[shell]','$_POST[count]','$_POST[accessed]','$_POST[modified]')"
However, there is much bigger problem in this code. You don't escape the values, therefore open an SQL injection. Just think what would happen if your password contains a single quote, such as test'123:
encode('test'123')
This is obviously a syntax error. In fact it allows anyone to execute arbitrary SQL expressions by crafting special parameters in $_POST.
So what you really should do is either escape everything you put into query or use PDO with placeholders. Check for example, this tutorial http://www.phpeveryday.com/articles/PDO-Positional-and-Named-Placeholders-P551.html

MySQL CHAR/VARCHAR won't store letters, but takes numbers just fine in my PHP script

I have been writing a script in PHP to take values from a form and store them in a MySQL table I created in the code, like this:
mysql_query("CREATE TABLE `userdetails` ( userid VARCHAR(10), field1 CHAR(33), field2 CHAR(33), field3 VARCHAR(34)");
This only executes once, as I don't have access to the site's cPanel or phpMyAdmin, just the FTP server details. I collect strings from three text boxes, and then delete the current contents.
mysql_query("DELETE FROM `userdetails` WHERE userid=$userid");
Next, I upload the strings to the MySQL server like this:
mysql_query("INSERT INTO `userdetails` (`userid`, `field1`, `field2`, `field3`) VALUES ($userid, $field1, $field2, $field3)")
With this script, I can get numbers to go on the database fine, but whenever I use a letter in the text box, it doesn't upload and the database field returns to NULL, I think.
From a little debugging, I can tell that the strings are storing the text box data fine, I can echo them and they display, with letters. It just doesn't upload. I have tried making a new table and trying again, that didn't work.
You are vulnerable to SQL injection attacks, and are building an incorrect query.
Consider:
$userid = 'foo';
produces
mysql_query("DELETE .... WHERE user=foo");
You probably don't have a field named foo in your database, so the query fails. Since you obviously lack ANY kind of error handling, you'll never see the database spit your query back out at you with the syntax error highlighted.
At bare minimum, you need
mysql_query("DELETE ... WHERE user='$userid'"); // note the quotes
and some error handling
$result = mysql_query(...) or die(mysql_error());
And you really should go read http://bobby-tables.com before someone pwns your server via your badly written scripts.

Insert Query is not inserting anything into the database

mysql_query("INSERT INTO new_emails (from,subject,message,to,filename,fileurl) VALUES ('$id','$stripsubj','$content','$toids','$upload_name','$att')");
Firstly, I am aware that mysql_query is depreciated, and I will be re-doing the whole script at some point in the near future to accommodate this.
My main problem is that this query is not currently inserting anything into the database, and I haven't the faintest clue why. Unfortunately I don't have access to any phpMyAdmin logs/SQL logs that can help me debug this problem.
I have been working on this for a while so I am hoping I have something pretty stupid and not noticed.
The columns inside "new_emails" are: id,from,savedtodb,subject,message,to,filename,fileurl
The ID is auto_increment, and savedtodb is CURRENT_TIMESTAMP, which is why I am leaving them out.
Have I done anything particularly stupid or is there a deeper reason why this isn't working?
Cheers in advance!
from and to are reserved words. You need backticks for them:
INSERT INTO new_emails (`from`, subject, message, `to`, filename, fileurl)
VALUES ('$id', '$stripsubj', '$content', '$toids', '$upload_name', '$att')
There are some possible errors:
1) You may not have selected the database using mysql_selct_db or while declaring the connection.
2) Maybe you didn't escape the single quotes. MySQL hates single quotes, and would make an error if it finds any in the input.

Categories