Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
What's wrong on that code? -- It's keep refusing to create account.
$query = "
INSERT INTO `accounts`(`username`, `dispname`, `email`, `password`, `type`, `blocked`, `points`)
VALUES ($disname,$username,$email,$password,1,false,0)";
$result = mysql_query($query);
if($result){
$Registered = "You have registered successfully.";
} else {
$ERROREMAIL = "There Were an Error Registering your email, please contact our support.";
}
I am totally confused.
By the way this is the structure of the database, hopefully someone helps.
CREATE TABLE `accounts` (
`id` int(11) NOT NULL,
`username` varchar(255) DEFAULT NULL,
`dispname` varchar(255) NOT NULL DEFAULT 'someone',
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`type` int(10) NOT NULL,
`blocked` tinyint(1) NOT NULL DEFAULT '0',
`points` int(10) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
ALTER TABLE `accounts`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `username` (`username`);
ALTER TABLE `accounts`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;
Try this Query:
$query = "INSERT INTO `accounts`
(`username`, `dispname`, `email`, `password`, `type`, `blocked`, `points`)
VALUES ('$disname','$username','$email','$password',1,0,0)";
What change?
Adding single quote on string variables.
Also changed the value of blocked column as 0.
OP's comment:
"$connection = mysqli_connect($DBHOST, $DBUSER, $DBPASS, $DBNAME); also mysqli_query($connection, $query); – Ahmed Alaa 1 hour ago"
2 things wrong here. You're connecting with mysqli_ then querying with mysql_.
$result = mysql_query($query);
which should read as
$result = mysqli_query($connection, $query);
Those different APIs do NOT intermix. You must use the same one from connecting to querying.
Can I mix MySQL APIs in PHP?
Then, missing quotes around your variables (for strings) in values.
VALUES ($disname,$username,$email,$password,1,false,0)";
which should read as:
('$disname','$username','$email','$password',1,false,0)
But that leaves you open to SQL injection.
Use mysqli_* with prepared statements, or PDO with prepared statements.
Consult these following links http://php.net/manual/en/mysqli.error.php and http://php.net/manual/en/function.error-reporting.php
and apply that to your code during testing.
This does not help you during testing in order to get the real error(s):
else {
$ERROREMAIL = "There Were an Error Registering your email, please contact our support.";
}
This will:
else {
echo "Error: " . mysqli_error($connection);
}
You can set it back to your original method once there are no more errors.
You need to pass strings as strings not as integers
Try this:
$query = "
INSERT INTO `accounts`(`username`, `dispname`, `email`, `password`, `type`, `blocked`, `points`)
VALUES ('$disname','$username','$email','$password',1,false,0)";
Thanks for you all.
Solution is as it is.
Updating your php version to PHp 7_0_0.
Updating phpmyadmin to 4_5_2.
Updating MySql to 5_6_27.
Update the usage of old mysql -> PDO.
Related
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 3 years ago.
I'm usually good at this, and while I was finishing my project; I ran into an error. PDO was giving me a syntax error, that I couldn't wrap my head around. Maybe I'm just tired, but this is driving me crazy.
This is what I'm using for my PHP code:
$records = $conn->prepare('INSERT INTO users (username, email, password, limit) VALUES (:username, :email, :password, :theLimit)');
$records->bindParam(':username', $_POST['username']);
$records->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
$records->bindParam(':email', $_POST['email']);
$records->bindParam(':theLimit', $_GET['amt']);
My database is as follows:
CREATE TABLE `users` (
`id` int(11) UNSIGNED NOT NULL,
`username` varchar(250) NOT NULL DEFAULT '',
`email` varchar(250) NOT NULL DEFAULT '',
`password` varchar(200) NOT NULL DEFAULT '',
`limit` varchar(200) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The error I get is this:
Array ( [0] => 42000 [1] => 1064 [2] => You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'limit) VALUES ('F', 'some_person#email.com', '$2y$10$gacC/a8zA3jCbPpKNTddtu4dBG' at line 1 )
And finally, the URL looks like this:
https://website.com/reg.php?serial=306019525D31&amt=10
I have even tried:
$records->bindParam(':theLimit', $_POST['email']);
thinking it might've been the URL. Same error.
I redid the database, same error.
Any ideas?
Thank you!
LIMIT is a reserved MySQL keyword, so you should escape it:
$sql = "INSERT INTO users (username, email, password, `limit`) ";
$sql .= "VALUES (:username, :email, :password, :theLimit)";
$records = $conn->prepare($sql);
Actually, you should avoid naming your objects using LIMIT or any other reserved keyword. Otherwise, you will always have to escape them as done above.
I have a mysql insert query which runs on aws RDS(Live env) but throws an error on my local(local env).
on local I'am using mysql V-5.6
$sql = "INSERT INTO `users` (`id`,
`name`,
`email`,
`pass`)
values('','omi','omi#gmail.com','123123')
id is not null and auto_increment.
The error which i get on local is 'Incorrect integer value: '' for column 'id' at row 1'
but when this executed on live env all the data gets inserted into table.
I cant understand what exactly is happening here. please help. thank you.
DDL of users table.
local
CREATE TABLE `users`
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(256) DEFAULT '',
`email` varchar(256) NOT NULL,
`pass` varchar(256) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=25986 DEFAULT CHARSET=utf8;
Live
CREATE TABLE `users` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(254) DEFAULT '',
`email` varchar(256) NOT NULL,
`pass` varchar(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=26046 DEFAULT CHARSET=utf8;
I believe the error is with those quotes (''). When you want to do an insert with an auto_increment field, you have to use null as argument in the auto_increment field position.
See if this works:
$sql = "INSERT INTO `users`
(`id`, `name`, `email`, `pass`)
values(null,'omi','omi#gmail.com','123123');
EDIT 1
Using null doesn't generate any error because internally the DBMS is prepared to receive such an argument. It understands that is its duty to generate the next number of the sequence and if it hasn't any, 0 (of type integer in your case) is inserted first. I know defining "not null" in the DDL of a field and then using "null" in the DML insert statement for that exact field may look confusing, but it's just the right way to use the auto_increment feature.
From the documentation:
If the column is declared NOT NULL, it is also possible to assign NULL to the column to generate sequence numbers.
Also, if using an empty string as argument in an statement doesn't generate any error, it could maybe be because RDS interface has an internal function that converts empty to null. Something like the nullif function in MySQL.
You can't do it like that. Either dont even mention 'id' or give it null value.
$sql = "INSERT INTO `users` (
`name`,
`email`,
`pass`)
values('omi','omi#gmail.com','123123')
OR:
$sql = "INSERT INTO `users` (`id`,
`name`,
`email`,
`pass`)
values('NULL','omi','omi#gmail.com','123123')
I am creating a web service which will be called from an android app. Actually I am trying to do an insert into my database but i can't figure out why it is not working. Here is my code, with some tests I have made in order to find the bug :
<?php
$con = mysqli_connect("localhost", "xxx", "xxx", "xxx");
/* here is the original code that I commented in order to do my tests
$mail = $_POST["mail"];
$mdp = $_POST["mdp"];
$nom = $_POST["nom"];
$prenom = $_POST["prenom"];
$dateNaissance = $_POST["dateNaissance"];
*/
$mail = "test#mail.fr";
$mdp = "test";
$nom = "test";
$prenom = "test";
$dateNaissance = "2000/01/01";
$statement = mysqli_prepare($con, "INSERT INTO utilisateur (mail, mdp, nom, prenom, dateNaissance) VALUES (?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "sssss", $mail, $mdp, $nom, $prenom, $dateNaissance);
mysqli_stmt_execute($statement);
$query = "SELECT * FROM utilisateur";
$result2 = mysqli_query($con, $query);
$final = mysqli_fetch_row($result2);
print_r($final);
?>
The SELECT request returns me the row I have in my utilisateur table so I suppose it's not a problem of connection.
Moreover, mysqli_stmt_execute($statement) returns 1... So if i'm not wrong it's supposed to mean that my request worked ? Anyway, nothing is inserted.
I'm hosting my database with 000webhost, don't know if this will help... I'm starting developing so everything is not crystal clear.
Hope that I was understandable and that you'll enlighten me!
I found what was wrong : everything was working really well... But i was connecting to the wrong database. Indeed I began my project in localhost and then used 000webhost hosting. I got confused since it was written "server : localhost" in the two phpMyAdmin interfaces and also because I had the exact same table in the two databases.
Thanks for the answers that still made me learn.
The query causes this error
Error: Field 'idUser' doesn't have a default value.
You will need to fix your table. Make it an InnoDB table.
CREATE TABLE `utilisateur` (
`idUser` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`mail` VARCHAR(40) COLLATE utf8_bin NOT NULL,
`mdp` VARCHAR(40) COLLATE utf8_bin DEFAULT NULL,
`nom` VARCHAR(40) COLLATE utf8_bin DEFAULT NULL,
`prenom` VARCHAR(30) COLLATE utf8_bin DEFAULT NULL,
`dateNaissance` DATE DEFAULT NULL,
PRIMARY KEY (`idUser`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
I have an existing table and I'm trying to insert data to it from a form submission.
I think I need another set of eyes to look over my code. There is an issue with it, at this point I'm not sure what.
I fill out the form, it appears to submit, I check the table and I get nothing. No data gets inserted.
If some of the values aren't being used right now, can that hinder the data from being inserted into the table? Shouldn't the form inputs that are on the form be inserted anyway? I tried to use only the values within the form, and that still did not work.
For example, right now the form inputs are only for first, last, title, genre, about, and picture. The rest only exist within the table. Data for the remaining fields cannot be currently entered at this time.
Hopefully someone has a solution?
$servername = "server";
$username = "user";
$password = "pass";
$dbname = "db";
if (isset($_POST['submit'])){
$conn = mysqli_connect($servername,$username,$password,$dbname);
if (!$conn) {
die("Connection failed: " . mysqli_error());
}
$first = mysqli_real_escape_string($conn, $_POST['First']);
$last = mysqli_real_escape_string($conn, $_POST['Last']);
$title = mysqli_real_escape_string($conn, $_POST['Title']);
$storylink = mysqli_real_escape_string($conn, $_POST['StoryLink']);
$genre = mysqli_real_escape_string($conn, $_POST['Genre']);
$about = mysqli_real_escape_string($conn, $_POST['About']);
$link = mysqli_real_escape_string($conn, $_POST['Link']);
$picture = mysqli_real_escape_string($conn, $_POST['Picture']);
$alt = mysqli_real_escape_string($conn, $_POST['ALT']);
$sql = "INSERT INTO ContrTemp (`First`,`Last`,`Title`,`StoryLink`,`Genre`,`About`,`Link`,`Picture`,`ALT`)
VALUES ('$first','$last','$title','$storylink','$genre','$about','$link','$picture','$alt')";
mysqli_query($conn, $sql) or die('Error: ' . mysqli_error($conn));
mysqli_close($conn);
}
Here is one input field from the form. The others are pretty much the same.
<input type="text" id="ContrTitle" name="Title" placeholder="Title" class="inputFields" style="width:650px;" />
Could there be an issue with the name within the input?
sql table structure:
CREATE TABLE IF NOT EXISTS `ContrTemp` (
`ID` int(5) NOT NULL AUTO_INCREMENT,
`First` varchar(40) COLLATE utf8_unicode_ci NOT NULL,
`Last` varchar(40) COLLATE utf8_unicode_ci NOT NULL,
`Title` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`StoryLink` varchar(140) COLLATE utf8_unicode_ci NOT NULL,
`Genre` varchar(11) COLLATE utf8_unicode_ci NOT NULL,
`About` varchar(2000) COLLATE utf8_unicode_ci NOT NULL,
`Link` varchar(125) COLLATE utf8_unicode_ci NOT NULL,
`Picture` varchar(500) COLLATE utf8_unicode_ci NOT NULL,
`ALT` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
Now I'm actually hitting the database, a record shows up, but no data was inserted. Before, No record was inserted at all.
You can try this one for inserting data
$sql = 'INSERT INTO ContrTemp (First,Last,Title,StoryLink,Genre,About,Link,Picture,ALT) VALUES ("'.$first.'","'.$last.'","'.$title.'","'.$storylink.'","'.$genre.'","'.$about.'","'.$link.'","'.$picture.'","'.$alt.'")';
I think you have done pretty well but one last try put these symbols [backticks] ` around your fields to understand mysql they are just fields.
$sql = "INSERT INTO ContrTemp (`First`,`Last`,`Title`,`StoryLink`,`Genre`,`About`,`Link`,`Picture`,`ALT`)
VALUES ('$first','$last','$title','$storylink','$genre','$about','$link','$picture','$alt')";
Your mysqli_error() is incorrect syntax, you need to specify the connection so have mysqli_error($conn) to properly feedback to you the SQL errors. As mentioned by Mitkosoft in comments some of your column names are MySQL keywords. It could be a good habit to get into to always encase column names in backticks.
So:
$sql = "INSERT INTO ContrTemp (`First`,`Last`,`Title`,`StoryLink`,`Genre`,`About`,`Link`,`Picture`,`ALT`)
VALUES ('$first','$last','$title','$storylink','$genre','$about','$link','$picture','$alt')";
mysqli_query($conn, $sql) or die('Error: ' . mysqli_error($conn));
Also you don't need to select db with mysqli_select_db($conn,$dbname); because the database is selected on the login command mysqli_connect above.
Further queries:
Is your database access account allowed to INSERT to this database?
Can you insert the same data as in your form directly into the database using an interface such as PHPMyAdmin, MySQL Workbench (Or whichever one you use to view the DB)?
I had hoped this had been as simple as the code I provided above, thus the reason I did not mention that this code was being used as part of a WordPress template. I did not think that would be come an issue as the template is pretty light weight.
With that said, I simply took my block of php code that handles the data insertion, and I placed it at the top of the template. Worked like a charm..
Yeah, I know, its common problem, but I cant solve it for last 3 hours.
I do this query:
$query = 'UPDATE `'.$masterapp_users_table.'` SET `login` = "'.htmlspecialchars(strip_tags($_POST['login'])).'", `pass` = "'.md5(htmlspecialchars(strip_tags($_POST['pass']))).'", `email` = "'.htmlspecialchars(strip_tags($_POST['email'])).'", `firstname` = "'.htmlspecialchars(strip_tags($_POST['fn'])).'", `secondname` = "'.htmlspecialchars(strip_tags($_POST['sn'])).'" WHERE `login` = "'.htmlspecialchars(strip_tags($_POST['previouslogin'])).'"';
echo $query.'<br />';
mysql_query($query) or die(mysql_error());
and I get this:
UPDATE `masterapp_users` SET `login` = "asdasdasd", `pass` = "a3dcb4d229de6fde0db5686dee47145d", `email` = "asdasdasd", `firstname`
= "asdasdasd", `secondname` = "asdasdasd" WHERE `login` = "88888881"<br />Unknown column 'login' in 'where clause'
But it changes the record!
Maybe someone can see what I cant see?
Oh! forgot to say: If I paste that string from browser to PMA, it works fine.
UPDATE:
CREATE TABLE IF NOT EXISTS `masterapp_users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`login` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
`pass` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
`firstname` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
`secondname` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`),
UNIQUE KEY `login` (`login`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=33 ;
The error means that the column in the MasterApp_Users table is not called login; it is Login or LOGIN or log_in or user or username or user_name or ...
In the statement that constructs the string, you have back-ticks:
UPDATE `'.$masterapp_users_table.'` SET `login` ...
In the echo, those back-ticks aren't showing.
If you use back-ticks like that, the column names become case-sensitive. What was the spelling of the CREATE TABLE statement precisely? Were column names written in mixed case inside back-ticks?
...Now we have the table schema shown, it is less explicable (not that it was easily explained before)...
Are you sure your browser and your PHP are connecting to the same database?
To debug further, I suggest changing:
The WHERE criterion to specify the id column and an appropriate value.
Do not SET the login column.
Check whether the UPDATE changes what you expect it to change.
If it doesn't change the record you think it should (but it does work), you have an issue identifying the database.
If you end up with a different column not being found, we can be pretty sure that there's a different table altogether. Maybe do a SELECT * FROM masterapp_users and review the column definitions returned.
If it changes the record, then we have a deep mystery on our hands.
It changes the record.
The complaint was specifically about the login column in the WHERE clause. If you specify id in the WHERE clause, are you able to set login in the SET clause of the statement?
If so, this is beginning to look like a bug in the DBMS. It is difficult to see why it could complain about login in WHERE and not in SET. Thus, it is unlikely to be the solution.
If the message changes to something roughly equivalent to 'unknown column login in the SET clause', then there is some self-consistency.
What happens if you rename the column in the table and modify the code accordingly?
Resolution
Comment N:
If it allows SET login = ... and not WHERE login = ... in a single statement, then I think you've got a bug. I'm surprised; it isn't like a DBMS (any DBMS) to be quite that capricious, so I'd need to be very sure about it before calling it a bug. It may also mean there's another factor at play here. If you add an echo "Hi" after the mysql_query() or die line, does that get through? Are you in fact debugging the wrong bit of SQL? Maybe there's a SELECT or something afterwards that's malformed?
Comment N+1:
Yeah thanks! After I add echo 'Hi'; after mysql_query, it appeared, so the problem was in my next queries. I knew that the problem was stupid. facepalm
Who's never made a similar mistake?
If my query works in phpMyAdmin but not from the code, the first thing I do is change
SELECT `column` FROM `table`
to
SELECT `column` FROM `database`.`table`
, or similarly with UPDATE queries of course. Perhaps this is your fix, and the MySQL error is just a bit cryptic.
Edit:
Furthermore, do not use htmlspecialchars nor strip_tags for your query escaping! It is insecure because this is not intended usage. To escape query values, it's better to use mysql_real_escape_string. Use the correct escape function for the correct application. I would write your query as follows:
$query = '
UPDATE `' . $masterapp_users_table . '`
SET `login` = "' . mysql_real_escape_string($_POST['login']) . '",
`pass` = "' . md5($_POST['pass']) . '",
`email` = "' . mysql_real_escape_string($_POST['email']) . '",
`firstname` = "' . mysql_real_escape_string($_POST['fn']) . '",
`secondname` = "' . mysql_real_escape_string($_POST['sn']) . '"
WHERE `login` = "' . mysql_real_escape_string($_POST['previouslogin']) . '"
';
// To display it in your browser:
echo htmlspecialchars($query) . '<br />';
// To run it:
mysql_query($query) or die(mysql_error());
This is just a friendly lesson. Wrong escape functions can lead to serious security holes.