MySQL UPDATE query, is this wrong? - php

been working all day on something and can't seem to get this right...
I have a key generation script in PHP that runs some if statements, selects a license, creates a key, inserts it into the database and then emails the user the output.
The key is inserting into the database fine, and the email even sends fine with the key in it. The variable for email is $email, and is declared at this point, because it gets used down below this query to send an email (which sends). However, I can't get this UDPATE query to work in between the two (yes, the key is already generated and inserted by now):
$username = $email;
mysql_query("UPDATE keys SET username='".$username."' WHERE key='".$userkey."'");
Username is varchar, 255.
HELP!

KEY is a reserved word in MySQL (e.g. PRIMARY KEY).
If you're going to use it as an identifier, you will have to surround the name with `backticks` in every query.
mysql_query("UPDATE `keys` SET username='".$username."' WHERE `key`='".$userkey."'");
http://dev.mysql.com/doc/refman/5.1/en/reserved-words.html

Both key and keys are reserved words in MySQL. You need to escape both with backticks:
mysql_query("UPDATE `keys` SET username='".$username."' WHERE `key`='".$userkey."'");

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.

MySQL SET DEFAULT returns error: query is empty

I have an existing MySQL (version 5.6.12) table called 'users' and am trying to set the column defaults via php (version 5.4.12), for example:
$query = "ALTER TABLE users ALTER username SET DEFAULT NULL";
$result = mysqli_query($query);
However this generates a SQL error (which results in the message 'query is empty'). 'username' is a VARCHAR(200) type column.
Using a quoted literal (such as 'John') for the default value results in the same error. (Just for kicks, though I am using MySQL I have also tried modifying the query according to SQL/MS Access or Oracle syntax but it still doesn't work).
What am I doing wrong?
EDIT: Problem solved. The above query is fine and nothing is wrong.
I made an incredibly dumb error and forgot $ sign in front of $query, i.e. my code was written $result = mysqli_query(query);
(Just so you know, I am a programmer with decades of experience.)
Change query like below
$query = "ALTER TABLE users MODIFY Column username VARCHAR(200) NULL DEFAULT NULL";
or
$query = "ALTER TABLE users CHANGE Column username username VARCHAR(255) NULL DEFAULT NULL";
I use this one for my website
$query = "ALTER TABLE 'users' CHANGE 'username' 'username' VARCHAR( 100 ) NULL DEFAULT NULL";
$result = mysqli_query($query);
Problem solved. The query is actually fine and nothing is wrong.
I made an incredibly dumb error and forgot $ sign in front of $query, i.e. my code was written $result = mysqli_query(query);
(Just so you know, I am a programmer with decades of experience.)
In MySQL you use backticked [`] quoted literals, don't use the quote sign [']. On the other side, every DDBB engine uses its slightly different flavour of SQL. Most of them anyway are able to interpret common subsets as described by the various active standards SQL89, SQL92, SQL99... and so on.
In short, your SQL is wrong, in regards to what MySQL expects it to be. You'll have to build your SQL skills on top of trial and error by working with different SQL engines, until you can give each of these engines the SQL variant they expect. Just don't give up and insist on the query. Simplify it, running shorter strings until you find one that works, then refine it by adding smaller pieces until you reach your objective.

Add column id to an existing table

I a trying to add column id which will be a primary key with auto increment properties. So i execute this SQL query:
ALTER TABLE `user_info` ADD `id` INT NULL AUTO_INCREMENT PRIMARY KEY FIRST ;
The column is created successfully and even creates id for the already existing data.
But i am unable to insert anything inside the table anymore.
<?php
require "init.php";
$name=$_POST["user"];
$user_email=$_POST["user_email"];
$user_pass=$_POST["user_pass"];
$sql_query="SELECT * FROM user_info WHERE user_email='$user_email'";
$check=mysqli_fetch_array(mysqli_query($con,$sql_query));
if(isset($check)){
$response["success"]=false;
$response["message"]="Email already exists";
echo json_encode($response);
}else{
$sql_query="insert into user_info values('$name','$user_email','$user_pass');";
if(mysqli_query($con,$sql_query)){
//echo "<h3> Data Insert success</h3>";
$response["success"]=true;
$response["message"]="Registration successful";
echo json_encode($response);
}
else{
$response["success"]=false;
$response["message"]="Registration unsuccessful";
echo json_encode($response);
}
}
?>
I googled around and found out that i could insert 0 or null in place of my id.
I purposefully read that :
In order to take advantage of the auto-incrementing capability of the column, do not supply a value for that column when inserting rows. The database will supply a value for you.
The code works well when i drop column id but when i add it, i get response as Registration unsuccessful within my json.
The workarounds from here or here did not seem to solve my problem.
What am i missing?
You have four columns in your table now, however you only provide three values. Checking mysqli_error would give you an error message telling you this.
You can either change your SQL to send NULL for the id which will create an appropriate id:
insert into user_info values(null, 'Foo','Foo#example.com','password');
Or, even better is to tell MySQL which columns you are targeting. This means in the future that if you add columns your SQL wont break:
insert into user_info (name,email, password)
values('Foo','Foo#example.com','password');
Note: There is some issues with your code. You are vulnerable to SQL injection - if someone sends a malicious value it could run SQL commands you don't intend.
Additionally storing passwords in plain text is not a good idea. You should be hashing them with a secure algorithm. See: http://php.net/manual/en/faq.passwords.php
Your INSERT syntax was correct before you added an ID column on first place:
$sql_query="insert into user_info values('$name','$user_email','$user_pass');";
But now you should specify the columns prior to the VALUES :
$sql_query="insert into user_info (name,email, password) values('$name','$user_email','$user_pass');";

PHP MySQL - INSERT and ON DUPLIATE KEY UPDATE with WHERE?

I want to be able for members to add more info (location, story) to their profile and also update their password if needed.
For that I use the following snippet:
$query = mysql_query("
INSERT INTO
members (location, story)
VALUES
('$location', '$story')
WHERE
username='$user'
ON DUPLICATE KEY UPDATE
hash = '$password',
location='$location',
story='$story'
");
This does not work with the "WHERE" part, but if I remove it then the data just gets filled into an empty record, not the user record. How do I properly use the WHERE part in this snippet, so the correct user profile is updated?
I have searched up and down the internet and this website, but not found a single solution, which surprises me as this seems to be a very common question?
Does anyone know how to solve this problem?
Thanks in advance!
First, mysql is deprecated, you should use mysqli.
Second, make sure you escape your values before entering them in queries. mysql_real_escape_string() is a bare minimum.
Third, INSERT / ON DUPLICATE KEY UPDATE does not accept WHERE clause.
It's use is for avoid duplicating keys.
For a simple user signup or whatever, you could avoid using IDs / auto increment and use username as primary key. But for this you'd need MyISAM or MySQL 5.6+ in order to have fulltext indexing, and in general, this is recommended.
But in this use case, your location and story would be always overwritten.
If this is what you want, you can try whatever I've written in the previous paragraph.
You can use a INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE construct like
INSERT INTO
members (location, story)
SELECT '$location', '$story'
FROM table_name
WHERE username='$user'
ON DUPLICATE KEY UPDATE
hash = '$password',
location='$location',
story='$story'
Ok, I was finally able to solve this problem on my own. For anyone who is interested, here is the code:
// if user entered location
if (!empty($_POST['location']))
{
// if database row empty
if ($row['location'] == " ")
{
mysql_query("INSERT INTO members (location) VALUES ('".$location."') WHERE username='".$user."'");
}
// if database row not empty
else
{
mysql_query("UPDATE members SET location='".$location."' WHERE username='".$user."'");
}
}
// if user entered story
if (!empty($_POST['story']))
{
// if database row empty
if ($row['story'] == " ")
{
mysql_query("INSERT INTO members (story) VALUES ('".$story."') WHERE username='".$user."'");
}
// if database row not empty
else
{
mysql_query("UPDATE members SET story='".$story."' WHERE username='".$user."'");
}
}

Alter table with PHP and MySQL, add a column with an '#' sign

I am trying to check if a table has a certain column in it, and if not add that column to it. My code appears to work fine as long as the input value does not have an # sign. I have tried surrounding
'$email'
with and without single quotes as an input string. Any help would be really appreciated.
$email = strtolower(mysql_real_escape_string($_SESSION['email']));
$result = mysql_query("SHOW COLUMNS FROM `selections` LIKE '$email'",$conn);
$exists = (mysql_num_rows($result))?TRUE:FALSE;
if ($exists == FALSE) {
$query2 = "ALTER TABLE selections ADD $email VARCHAR( 120 ) NOT NULL";
$add= mysql_query($query2,$conn);
var_dump($query2);
echo("this error". mysql_error());
}
$query2 was taken directly from phpmyadmin and seems to work there even with an # sign input
Thanks for your help!
Before anything else, please, please consider doing this in another way. You will be adding a field to a table for every email - what you probably do not know is that this increases the size of your table by increasing the size of the rows, and also limits you to a fixed number of fields (This link clearly highlights a total of 65535 bytes per row max. Every VARCHAR character, depending on charset, is between 3 and 8 bytes)
The real reason why your request is failing is because # is a special character in your SQL queries and phpmyadmin happens to be smart enough to escape it. # denotes a variable in the SQL dialect uses by MySQL. You can either backtick-escape it for MySQL, or you can quit using this in favour of a table structure like this:
selection:
* id
* your metadata here
emails:
* id
* email_address
selection_emails:
* id
* selection_id
* email_id
The third table is called an associative table. It allows you to keep normalizing your data.
You can surround the email with curly brackets {$email} to define it explicitly as a variable within a string, but you probably also need to escape odd characters in this variable before this.
When altering the table you should also surround this with back-ticks, to allow for odd characters.
The best approach would be to use parameterized queries, and drop the DEPRECATED mysql library. And also to not allow odd characters to be used in field names.
I would also question why you are adding email as a new column.

Categories