it says success but it doesnt really insert the values to Database. idk whats going on.
if($_POST['submit']){
$registerQuery = 'INSERT INTO `user`(firstname`, `lastname`, `email_address`, `password`, `mobile_number`,`location`) VALUES (
"'.$firstname.'",
"'.md5($password).'",
"'.$lastname.'",
"'.$emailaddress.'",
"'.$password.'",
"'.$mobile_number.'",
"'.$location.'");';
echo 'Success';
}
$qry = mysql_query($registerQuery);
Your echo statement is not wrapped in a conditional, and runs before the query is executed. As a result "Success" will be echoed no matter what.
Instead, you want to check the response of mysql_query to see whether it executed successfully, then take action (like echoing 'Success') based on that result.
mysql_query() always returns false on error, so you can check $qry to see if it is false:
if ($qry === false) {
echo "Query failed";
// take action as needed
}
else {
echo "Success";
// take action as needed
}
To see the exact error that caused the failure, use mysql_error(). You can execute this in the 'failed' section of code, above.
In this case, the failure was caused by two errors in your query:
Syntax
There is a missing backtick before 'firstname':
'INSERT INTO `user`(firstname`,
should be
'INSERT INTO `user`(`firstname`,
Column/Value Count Mismatch
Your query specifies that six columns will be filled:
(`firstname`, `lastname`, `email_address`, `password`, `mobile_number`,`location`)
but seven values were provided:
"'.$firstname.'",
"'.md5($password).'",
"'.$lastname.'",
"'.$emailaddress.'",
"'.$password.'",
"'.$mobile_number.'",
"'.$location.'");'
Deprecation Warning
Note: The mysql_* functions are deprecated; they have been replaced by PDO. Consider for safety and stability, consider modifying your code to use PDO.
It doesn't work because there are 7 values and 6 columns and you miss a backtick around the firstname column. The number of values and columns must be the same. You always echo Success because you don't check if $qry is false (it returns false on error). Finally, you should not use mysql_* functions because they are officially deprecated as of PHP 5.5. Use either PDO or MySQLi.
you are also missing a back-tick surrounding firstname...
should be:
$registerQuery = 'INSERT INTO `user`(`firstname`, `lastname`
Related
I don't know what is wrong.
$result = $db->query("INSERT INTO post_items(`post_id`,`content`,`date`,`user_id`,`category_id`)
VALUES ('".$postid.", '".$content."', '".$date."', '".$user_id."', '".$category_id."')");
if($result) {
echo "hey";
}
How can I use mysqli_error function to check the cause of error? The syntax of PHP is just fine I think. I guess it has problem with my database.
You have a problem with single quotes. You have a ' just before your $postid, but not one after. This means that the SQL query will be seeing '$postid, ' as your first variable and then being confused about the remained.
Try changing your SQL to read:
$result = $db->query("INSERT INTO post_items(`post_id`,`content`,`date`,`user_id`,`category_id`)
VALUES ('".$postid."', '".$content."', '".$date."', '".$user_id."', '".$category_id."')");
Hope that helps.
I am using the following script to enter data into my database from a form. I have echo'd each of the values declared at the beginning and they are all coming across just fine.
include("connectmysqli.php");
echo '<link rel="stylesheet" href="http://towerroadacademy.co.uk/templates/rt_reflex_j16/css/template.css">';
if (isset($_GET['questionnaireID'])) {$questionnaireID = $_GET['questionnaireID'];}else {$questionnaireID = '';}
if (isset($_POST['newquestionnumber'])) {$questionnumber = $_POST['newquestionnumber'];}
if (isset($_POST['questionID'])) {$questionID = $_POST['questionID'];}else {$questionID = '';}
if (isset($_POST['question'])) {$question = $_POST['question'];}else {$question = '';}
if (isset($_POST['lowerlabel'])) {$lowerlabel = $_POST['lowerlabel'];}else {$lowerlabel = '';}
if (isset($_POST['middlelabel'])) {$middlelabel = $_POST['middlelabel'];}else {$middlelabel = '';}
if (isset($_POST['upperlabel'])) {$upperlabel = $_POST['upperlabel'];}else {$upperlabel = '';}
$stmt = $db->prepare("INSERT INTO `QuestionnaireQuestions` (`questionnaireID`, `questionnumber`, `questionID`, `question`, `lowerlabel`, `middlelabel`, `upperlabel`) VALUES ($questionnaireID', '$questionnumber', '$questionID', '$question', '$lowerlabel', '$middlelabel', '$upperlabel') WHERE questionnaireID='$questionnaireID';");
if (!$stmt) trigger_error($db->error);
$stmt->execute();
I keep getting the following error though and cant seem to trace what is causing it.
Notice: 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 '', '3', '1947679104', 'questonofngdfngodfngo', 'lower', 'midddle', 'upper') WHER' at line 1 in /home2/towerroa/public_html/questionnaires/addanotherquestionsubmit.php on line 16 Fatal error: Call to a member function execute() on a non-object in /home2/towerroa/public_html/questionnaires/addanotherquestionsubmit.php on line 17
The table QuestionnaireQuestions looks like this :
id questionnaireID questionnumber questionID question lowerlabel middlelabel upperlabel
You're missing a quote on $questionnaireID:
INSERT INTO `QuestionnaireQuestions` (`questionnaireID`, `questionnumber`, `questionID`, `question`, `lowerlabel`, `middlelabel`, `upperlabel`) VALUES ('$questionnaireID', '$questionnumber', '$questionID', '$question', '$lowerlabel', '$middlelabel', '$upperlabel')
Also remove the WHERE clause.
UPDATE statements can use the WHERE statement to update existing database records based upon a condition. Granted INSERT SELECT statements can contain a WHERE, INSERT statements by themselves do not.
INSERT will not work with the WHERE condition,if only you want to UPDATE the row then you can use WHERE condition and replace this
VALUES ($questionnaireID',......
with
VALUES ('$questionnaireID',
You have missed a single quote and remove ';' from the end also.Now the query will be
$stmt = $db->prepare("INSERT INTO `QuestionnaireQuestions` (`questionnaireID`,
`questionnumber`, `questionID`, `question`, `lowerlabel`,
`middlelabel`, `upperlabel`) VALUES ('$questionnaireID',
'$questionnumber', '$questionID', '$question', '$lowerlabel',
'$middlelabel', '$upperlabel')");
But I must appreciate that you are using PDO statements instead of mysql_* deprecated functions
($questionnaireID'
should be
('$questionnaireID'
but you should really try working with prepared statements
I'm new to sql and PHP. So far have been able to figure things out but the PREPARE statement is giving me syntax issues (maybe because I'm trying to do several things in one step). If someone could let me know where my syntax is messing up that would be great.
In addition the code I'm writing is trying to update save files on a server and while I believe doing it with a prepare statement is the correct way I would be happy to hear if it is not. Note I plan to change INSERT INTO -> a conditional insert or update.
The error I get is unexpected T_STRING. I've marked the line of the error in the code.
$sql='PREPARE statement FROM "INSERT INTO buildings VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) WHERE id="$id" AND ind="$i""';
$result=mysql_query($sql);
for($i=0;$i<1600;$i+=1){
if(isset($_POST['ind'.$i])){
$bind=$_POST['bind'.$i];
$time=$_POST['time'.$i];
$level=$_POST['level'.$i];
$p1ind=$_POST['p1ind'.$i];
$p1state=$_POST['p1state'.$i];
$p1time=$_POST['p1time'.$i];
$p2ind=$_POST['p2ind'.$i];
$p2state=$_POST['p2state'.$i];
$p2time=$_POST['p2time'.$i];
$p3ind=$_POST['p3ind'.$i];
$p3state=$_POST['p3state'.$i];
$p3time=$_POST['p3time'.$i];
$p4ind=$_POST['p4ind'.$i];
$p4state=$_POST['p4state'.$i];
$p4time=$_POST['p4time'.$i];
$p5ind=$_POST['p5ind'.$i];
$p5state=$_POST['p5state'.$i];
$p5time=$_POST['p5time'.$i];
$sql = 'SET #bind="$bind",'. //<-line of error
'#time="$time",'.
'#level="$level",'.
'#p1ind="$p1ind",'.
'#p1state="$p1state",'.
'#p1time="$p1time",'.
'#p2ind="$p2ind",'.
'#p2state="$p2state",'.
'#p2time="$p2time",'.
'#p3ind="$p3ind",'.
'#p3state="$p3state",'.
'#p3time="$p3time",'.
'#p4ind="$p4ind",'.
'#p4state="$p4state",'.
'#p4time="$p4time",'.
'#p5ind="$p5ind",'.
'#p5state="$p5state",'.
'#p5time="$p5time",'.
'#id="$id",'.
'#ind="$i"';
$result=mysql_query($sql);
$sql='EXECUTE statement USING #id,#time,#level,#p1ind,#p1state,#p1time,#p2ind,#p2state,#p2time,#p3ind,#p3state,#p3time,#p4ind,#p4state,#p4time,
#p5ind,#p5state,#p5time,#ind,#bind';
$result=mysql_query($sql);
if(!$result){
die("saveArry[0]=".mysql_error().";");
}else{
die("saveArry[0]='saved';");
}
}
}
$sql='DEALLOCA PREPARE statement';
$result=mysql_query($sql);
Update I am unable to install PDO on my hosts servers and therefore PDO is unfortunately an unacceptable solution. My answer (now with no errors!):
if(isset($_POST['ind'])){
$ind=sanitizeString($_POST['ind']);
$bind=sanitizeString($_POST['bind']);
$time=sanitizeString($_POST['time']);
$level=sanitizeString($_POST['level']);
$p1ind=sanitizeString($_POST['p1ind']);
$p1state=sanitizeString($_POST['p1state']);
$p1time=sanitizeString($_POST['p1time']);
$p2ind=sanitizeString($_POST['p2ind']);
$p2state=sanitizeString($_POST['p2state']);
$p2time=sanitizeString($_POST['p2time']);
$p3ind=sanitizeString($_POST['p3ind']);
$p3state=sanitizeString($_POST['p3state']);
$p3time=sanitizeString($_POST['p3time']);
$p4ind=sanitizeString($_POST['p4ind']);
$p4state=sanitizeString($_POST['p4state']);
$p4time=sanitizeString($_POST['p4time']);
$p5ind=sanitizeString($_POST['p5ind']);
$p5state=sanitizeString($_POST['p5state']);
$p5time=sanitizeString($_POST['p5time']);
$rot=sanitizeString($_POST['rot']);
$sql="INSERT INTO buildings (id,ind,bind,time,level,p1ind,p1state,p1time,p2ind,p2state,p2time,p3ind,p3state,p3time,p4ind,p4state,p4time,p5ind,
p5state,p5time,rot) VALUES ('$id','$ind','$bind','$time','$level','$p1ind','$p1state','$p1time','$p2ind','$p2state','$p2time','$p3ind','$p3state',
'$p3time','$p4ind','$p4state','$p4time','$p5ind','$p5state','$p5time','$rot') ON DUPLICATE KEY UPDATE bind='$bind',time='$time',level='$level',
p1ind='$p1ind',p1state='$p1state',p1time='$p1time',p2ind='$p2ind',p2state='$p2state',p2time='$p2time',p3ind='$p3ind',p3state='$p3state',
p3time='$p3time',p4ind='$p4ind',p4state='$p4state',p4time='$p4time',p5ind='$p5ind',p5state='$p5state',p5time='$p5time',rot='$rot'";
$result=mysql_query($sql);
if(!$result){
die("saveArry[0]=".mysql_error().";");
}else{
die("saveArry[0]=saved;");
}
}
The single and double quotes are interchanged in that line, should be,
$sql = "SET #bind='$bind',
#time='$time',
#level='$level',
#p1ind='$p1ind',
#p1state='$p1state',
#p1time='$p1time',
#p2ind='$p2ind',
#p2state='$p2state',
#p2time='$p2time',
#p3ind='$p3ind',
#p3state='$p3state',
#p3time='$p3time',
#p4ind='$p4ind',
#p4state='$p4state',
#p4time='$p4time',
#p5ind='$p5ind',
#p5state='$p5state',
#p5time='$p5time',
#id='$id',
#ind='$i'";
I strongly recommend using PDO instead of deprecated mysql_* functions. It is doing the hard work with prepared statements for you transparently.
As EthanB pointed out in comment, your code is vulnerable to SQL injection as you are inserting the values directly from user input ($_POST variable).
With PDO your code would look something like this (simplified):
$statement = $pdo->prepare("INSERT INTO buildings VALUES(:ind, :bind, :time, :level, ...) WHERE id = :id AND ind = :ind");
for( ... ) {
$statement->execute(array(
":ind" => $_POST["ind" . $i],
":bind" => $_POST["bind" . $i], ...
));
}
The PDO will send the PREPARE and EXECUTE queries for you and escape all parameters to prevent SQL injection.
I have this query:
mysql_query("INSERT INTO `63_Activity` (`username`, `time`) VALUES (`$usernann2`, `$date`)");
However, it doesn't do anything. Even when I tried correcting the variables to
". $variable ."
I checked the variables.
I copied the little line of code from somewhere it works.
The database and tables are existing.
I just thought I had things under control, then that happened -.-
Thank you in advance.
PS: I tried adding or die() - but no error. Nothing.
Values need to be in single quotes ('), not backticks (`)
mysql_query("INSERT INTO `63_Activity` (`username`, `time`) VALUES ('$usernann2', '$date')");
You should also make sure you're sanitizing your inputs, as well as preferably not using the mysql_ functions in place of mysqli_
You would be better off using Paramaterized queries as in the following example:
<?php
try {
$usernann2 = "whateverUsernameFits";
$date = new DateTime('2000-01-01');
$stmt = $this->db->prepare ( "INSERT INTO 63_Activity (username, time) VALUES (:usernann2, :date)");
$stmt->bindParam ( ':usernann2', $usernann2 );
$stmt->bindParam ( ':date', $date );
$stmt->execute ();
}catch ( PDOException $e )
{
throw new Exception ( $this->db->errorInfo () . 'Problem inserting object ' );
} catch ( Exception $e ) {
throw new \Exception ( 'Problem inserting object ' );
}
?>
Bound parameters are a staple in preventing SQL Injection attacks. The exceptions thrown would give you a clue as to what might be the problem in your query if there is one. I normally check the query first to make sure it's working with real values. From there it is a process of elimination.
PS. https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet for more information on SQL Injection. You should also be able to find some excellent information and questions here on Stackoverflow regarding SQL Injection.
try to put the query in a variable and echo it, and see if anything wrong, try to run it on php my admin also
I am trying to insert values in database and values are not being inserted, here is the code i have:
$user_name = "username";
$password = "password";
$database = "database";
$server = "localhost";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = 'INSERT INTO table (anInt, DomainName, URL, Rank, PageRank, Google, Bing, Boss, IndexedPage, Backlinks) VALUES ($anInt, $Domain, $URL, $Rank, $Pagerank, $Google, $Bing, $Yahoo, $Pages, $backlinks)';
$result = mysql_query($SQL);
mysql_close($db_handle);
print "Records added to the database";
it is printing that records added to the database but when looking at the database nothing is being added. some of the values are doubles, text, and ints. Is there anyway to debug this? I will be adding more information to the post if someone asks me to.
and of course I have an else statement i just thought it is not relevant since it is telling me that records are added.
First of all, you should escape the string values you are passing into the SQL query, using mysql_real_escape_string.
Then, you should add quotes, in your SQL query, arround the fields that are meant to contain strings.
I don't really know which fields are integers and which fields are strings, but you should be using something like this to build your SQL query :
// Escape the string data, and make sure integer really contain integers
$anInt = intval($anInt);
$Domain = mysql_real_escape_string($Domain);
$URL = mysql_real_escape_string($URL);
$Rank = intval($Rank);
$Pagerank = = intval($Pagerank);
$Google = intval($Google);
$Bing = intval($Bing);
$Yahoo = intval($Yahoo);
$Pages = intval($Pages);
$backlinks = intval($backlinks );
// Build the SQL query, using the "safe" variables
$SQL = 'INSERT INTO table (anInt, DomainName, URL, Rank, PageRank, Google, Bing, Boss, IndexedPage, Backlinks)
VALUES ($anInt, '$Domain', '$URL', $Rank, $Pagerank, $Google, $Bing, $Yahoo, $Pages, $backlinks)';
This is supposing that only DomainName and URL are meant to contain strings -- you might have to use mysql_real_escape_string and add quotes arround the values for some other fields too, if needed.
Then, you should take a look at the return value of mysql_query : for an insert query, in case of an error, it'll return false.
Here, if your $result variable is false, you should use mysql_error and mysql_errno : they'll allow you to know what error happened -- it will help detecting errors in your SQL query, for instance.
If this doesn't solve the problem, you should try outputting the SQL query, and run it using something like phpMyAdmin, to make sure it's OK.
I am no PHP expert, but I have 2 remarks.
You don't check the error (perhaps with mysql_errno()) so you don't know whether the records were added
I think the values, if they are strings, should be given like
'$Domain'
that is, escaped with ' characters.
better would be, of course, using something like
$sql = sprintf("INSERT ... VALUES(%d, '%s', '%s',...)",
$anInt, mysql_real_escape_string($Domain), ...);
if you insert user-supplied input.
You could examine the $result:
$result = mysql_query($query);
if (!$result) {
print "An error occured: " . mysql_error() . "\n";
}
My guess is that you're passing a string without quotes, like:
VALUES (Hello)
where you should pass it like:
VALUES ('Hello')
Like the commenter said, if the user can control these strings, you are open to an SQL Injection attack. You can prevent that attack by escaping the strings, for example:
$query = sprintf("INSERT INTO table (DomainName) VALUES ('%s')",
mysql_real_escape_string($domain_name));
In SQL queries, you need to enquote strings correctly, or it will produce an error. So all your variables that are used to store non-int or non-boolean values in the database need quotes around the values.
Additionally you should make sure that SQL injections are not a problem by escaping all values with mysql_real_escape_string first.
Apart from sql injections your error handling is not complete...
if (!$db_found) {
echo "datbase not found.";
}
else {
$SQL = 'INSERT INTO
table
(...)
VALUES
(...)
';
$result = mysql_query($SQL, $db_handle);
if ( !$result ) {
echo "error: ", mysql_error($db_handle);
}
else {
print "Records added to the database";
}
}
mysql_close($db_handle);
In case a query causes an error mysql_query() return FALSE and mysql_error() will tell you more about the error.
Well there are security issues with the code but to address one problem
you are not enclosing your string values in quotes in the SQL statement.
First of all, please regard everybody else's advice on safe database handling and avoiding injection.
The reason your query isn't doing anything is probably that you enclosed the string in single quotes. In PHP single quotes enforce the string to be literal. Unlike when using double quotes, variables will NOT be substituted. So '$foo' represents the sequence of characters '$'.'f'.'o'.'o'. "$foo" on the other hand represents the sequence of characters of whatever the variable $foo contains at the time of the string's definition.
You can use mysql_error() to catch most problems with MySQL. Even if the message isn't helping you, you at least know whether the query was parsed properly, i.e. on which end of the connection the problem lies.