I am currently looking to run a basic insert query using PHP to submit HTML form data to MySQL database.
Unfortunately however the insert process isnt running.
In my Insert syntax I have tried including $_POST[fieldname], ive tried including variables as below, and ive even played around with different apostrphes but nothing seems to be working.
as a side dish, im also getting truck load of wamp deprication errors which is overwhelming, ive disabled in php.ini and php for apache.ini file and still coming up.
If anyone can advise what is wrong with my insert and anything else id be much thankful.
Ill keep this intro straightfoward.
Person logs in, if they try to get in without login they go back to login page to login.
I connect to database using external config file to save me updating in 50 places when hosting elsewhere.
Config file is working fine so not shown below.
database is called mydb.
Im storing the text field items into variables, then using the variables in the insert query.
unitID is an auto increment field so I leave that blank when running the insert.
Unfortunately nothing is going in to the mysql database.
Thanks in advance.
PS the text fieldnames are all correctly matched up
<?php
//Start the session
session_start();
//check the user is logged in
if (!(isset($_SESSION['Username']) )) {
header ("Location: LoginPage.php?i=1");
exit();
}
//Connect to the database
include 'config.php';
$UserName = $_SESSION['Username'];
$UserIdentification = $_SESSION['UserID'];
if(isset($_GET['i'])){
if($_GET['i'] == '1'){
$tblName="sightings";
//Form Values into store
$loco =$_POST['txtloco'];
$where =$_POST['txtwhere'];
$when =$_POST['txtdate'];
$time =$_POST['txttime'];
$origin =$_POST['txtorigin'];
$dest =$_POST['txtdest'];
$headcode =$_POST['txtheadcode'];
$sql= "INSERT INTO sightings (unitID, Class, Sighted, Date, Time, Origin, Destination, Headcode, UserID) VALUES ('','$loco', '$where', '$when', '$time', '$origin', '$dest', '$headcode', '$UserIdentification')";
mysql_select_db('mydb');
$result=mysql_query($sql, $db);
if($result){
$allocationsuccess = "Save Successful";
header ('Refresh: 2; url= create.php');
}
else {
$allocationsuccess = "The submission failed :(";
}
}
}
?>
"unitID is an auto increment field so I leave that blank when running
the insert"
That's not how it works. You have to omit it completely from the INSERT statement. The code thinks you're trying to set that field to a blank string, which is not allowed.
$sql= "INSERT INTO sightings (Class, Sighted, Date, Time, Origin, Destination, Headcode, UserID) VALUES ('$loco', '$where', '$when', '$time', '$origin', '$dest', '$headcode', '$UserIdentification')";
should fix that particular issue. MySQL will generate a value automatically for the field and insert it for you when it creates the row.
If your code had been logging the message produced by mysql_error() whenever mysql_query() returns false then you'd have seen an error being generated by your query, which might have given you a clue as to what was happening.
P.S. As mentioned in the comments, you need to re-write your code with a newer mysql code library and better techniques including parameterisation, to avoid the various vulnerabilities you're currently exposed to.
Related
Have the following code that's executed when a script is ran. (I've just changed the login for display purposes).
<?php
$conn = mysql_connect("localhost", "root", "pw123");
mysql_select_db("test_db", $conn);
$sql = "INSERT INTO test_table (fname)
VALUES ('$fname')";
mysql_query($sql);
mysql_close($conn);
?>
I've edited the code down slightly so it doesn't show every value I'm trying to enter, but essentially, everything is entering as a blank value, or in the case of numerical inputs is defaulting to 0. I can't seem to figure out why this is. The variables are definitely not blank before hand as I've got them out putting on the web page to test as such.
For reference I assign $fname a value when the input box is changed using :
fname = $("#fname").val();
(Posted on behalf of OP):
Solved this myself anyway, instead of executing the MySQL statements in the initial page that user enters data, I moved it to the secondary web page, which opens once a user has submitted their information.
$fname is empty in your script and you need declarate the variable before:
$fname = 'David';
$sql = "INSERT INTO test_table (fname) VALUES ('$fname')";
:)
I have run into a small problem which I can't seem to figure out.
I am creating an application that when a user clicks a button, depending on which button they click, it will post a number into the database.
There are 9 numbers (0-9) and if they click 0 then 0 gets put into the database, if they click 1 then 1 gets put into the database, etc...
I have an onclick call using JQuery and Ajax to submit the data silently:
$(function(){
$('#1A').click(function(e) {
alert("You clicked 1A");
var poll_ans = 1;
$.ajax
({
url: 'postpoll.php',
data: {"pollAns": poll_ans},
type: 'post',
success: alert("Submitted " + poll_ans)
});
});
});
This works fine, and when I click the DIV with ID 1A I get the alert, and the "Submitted!" alert.
However, it does not post to the SQL Database. When I test the postpoll.php file by itself setting the variables in the URL it seems to load indefinitely.
Here is my code:
postpoll.php
<?php
session_start();
$mysqli=mysqli_connect("***","***","***","***");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isSet($_POST['pollAns']))
{
$answer=intval($_POST['pollAns']);
$query = "INSERT INTO test VALUES '$answer'";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
}
?>
Not sure what the problem is here - I am sure I missed something, and it's probably a simple solution!
Also, a side note - I eventually want to make it where the can only vote once, would the best way to accomplish this to simply set a cookie, then check if that cookie is present before posting? I know they could circumvent this by clearing their cookies, but it's not a problem.
SOLUTION:
It would appear that the culprit was CloudFlare. After checking on the httpd.conf file it showed that the sql connection was timing out. This was due to the fact that I was trying to connect to the DB using the actual URL, which is routed through CloudFlare's servers. In order to get to the actual physical server, I ended up using the IP. You can also add a DNS record that points to the IP and make sure you have it not being routed through CloudFlare.
Suggested Action in the Future: Remember that you are using CloudFlare!
When you establish the connection you name it $con, then you try to query using the variable $mysqli. Change $con to $mysqli when establishing the connection. I also changed VALUE to VALUES and added single brackets around $answer.
<?php
session_start();
$mysqli=mysqli_connect("***","***","***","***"); // Change from $con to $mysqli
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isSet($_POST['pollAns']))
{
$answer=intval($_POST['pollAns']);
$query = "INSERT INTO test VALUES '$answer'"; // Add single brackets around $value and changed VALUE to VALUES
$result = $mysqli->query($query) or die($mysqli->error.__LINE__); // Here you are using $mysqli to perform query
}
?>
Make sure your login credentials are correct. Also you have not properly handled the success and error events in your ajax request and alert the error message you get.
Try "isset" instead of "isSet", also set a session in the if statement. if (isset($_POST['pollAns'])) { $_SESSION['verify'] = "true"; } then echo $_SESSION['verify'] to see if the page is even getting to the sql statement.
See if changing the $mysqli->query($query) to this changes anything: $result = mysqli_query($mysqli, $query); (this shouldn't, I know that both ways work)
Also, a side note - I eventually want to make it where the can only vote once, would the best way to accomplish this to simply set a cookie, then check if that cookie is present before posting? I know they could circumvent this by clearing their cookies, but it's not a problem.
You can check the table first to see if that users IPAddress is listed:
$sq = "select * from test where IPAddr = '".$_SERVER['REMOTE_ADDR']."'";
$qu = mysqli_query($mysqli,$sq);
// if it does then the mysqli_num_rows will return 1 or greater.
if (mysqli_num_rows($qu) == 0) {
$query = "Insert into"...
}
It would appear that the culprit was CloudFlare. After checking on the httpd.conf file it showed that the sql connection was timing out. This was due to the fact that I was trying to connect to the DB using the actual URL, which is routed through CloudFlare's servers. In order to get to the actual physical server, I ended up using the IP. You can also add a DNS record that points to the IP and make sure you have it not being routed through CloudFlare.
Suggested Action in the Future: Remember that you are using CloudFlare!
I have created a form in HTML and the action is set to a php script. I'm pretty new to php and was wondering if someone could help me out with it? I need to write a script to add the info from the form to a database. I need to create the database and the table as well. I did a lot of reading on the net and I'm still unable to do it. This is the script I have. Please tell me what mistakes I have made. Thank you for all the help.
<?php
$con=mysql_connect("example.com","peter","abc123","my_db");
$sql="CREATE DATABASE user";
if (mysql_query($con,$sql)) {
echo "Database user created successfully";
}
$sql="CREATE TABLE Persons(PID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(PID),firstName CHAR(30),lastName CHAR(30),age INT, dateofbirth DATE, email CHAR(30)";
if (mysql_query($con,$sql)) {
echo "connected to database";
}
$sql="INSERT INTO Persons (firstName, lastName, age, dateofbirth, email) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]','$_POST[dateofbirth]','$_POST[email]')";
if (mysql_query($con,$sql)) {
echo "added to database";
}
mysql_close($con);
?>
I tried all the suggested answers and still not able to do it. Can someone please provide the code to do that? I need to obtain data from a form and insert it into a database using php!
Hi Try This Code,
$con=mysql_connect("example.com","peter","abc123");
$sql="CREATE DATABASE user";
if (mysql_query($sql))
{
echo "Database user created successfully";
}
1.- Don't use mysql_ functions because are deprecated, use mysqli_ functions or PDO instead.
2.- You have several error i guess, first of all you select a database my_db on the connection script, but you are created another database in the next line... it's very strange this behaviour. If this script executes every time then you should change your code (you can't create a database and a table every time.
In the insert string you have an error with the post code, try this:
$sql="INSERT INTO Persons (firstName, lastName, age, dateofbirth, email) VALUES ('{$_POST['firstname']}','{$_POST['lastname']}','{$_POST['age']}','{$_POST['dateofbirth']}','{$_POST['email']}')";
Your CREATE TABLE query will fail because of syntax error. You have to check queries results especially when next query depends on previous (and you're doing operations like creating databases/tables).
Next thing to change is mysql_*. This functions are deprecated and instead you should use PDO or mysqli_* (they are not hard to learn, just try).
And one more important change have to be done in your script. You're getting user input and adding it to query. Don't do that! You have to always assume that user is trying to hack you, so all inputed data have to be checked and filtered. Also it's good to use prepared statements with such data.
if (mysql_query($con,$sql)){
echo "Database user created successfully";
} else {
echo 'Error creating database - ' . mysql_error();
}
Same thing for all your sql statements to see where you went wrong
Change your code (mysql_query($sql)) instead of (mysql_query($con,$sql))
Kinda new to mysql and php
I have a hit counter for each page on my site and a private page that list all pages and hits.
I have a button that will reset all pages to zero and next to each page listing I have a reset button that will reset each page individually. This all was using a text file but now I am swtching to mysql database. I have coded the "RESET ALL" button to work but can not get the individual page buttons to work.
the processing code is:
if($_POST[ind_reset]) {
$ind_reset = $_POST[ind_reset];
mysql_connect("server", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$sql = 'UPDATE counters SET Hits =\'0\' WHERE Page = \'$ind_reset\';';
}
and the html form code is a string:
$page_reset = "<form id='Reset' action='counter_update.php' method='post'>
<button type='submit' name='ind_reset' value='$formPage'>RESET</button>
</form>";
Let's start with the first thing:
if($_POST[ind_reset]) {
should be
if($_POST['ind_reset']) {
It works without quotes because PHP is silently correcting your error. If you turned error reporting to E_ALL, you would get to see the error message.
One thing that you need to consider is that you can never trust POST data to be what you think it's supposed to be. Maybe you put in a typo. Maybe a hacker is sending you fake POST data. Whichever it is, it will mess up your code if the wrong thing gets put in that database update. For this reason, instead of simply plugging in that POST value into your database, you should have a checker to make sure that the value is a valid one. When I do things like this, I make an array of possible values and use only those values when updating or inserting into the database. Example:
$pages = array('value_on_page'=>'value_put_in_database',
'xyz'=>'thing_in_database_2');
//the valid things to post are either 'value_on_page' or 'xyz',
//but what goes into the database are the values those keys point to
//e.g. if $_POST['ind_reset'] == 'xyz', $ind_reset will be 'thing_in_database_2'
$key = $_POST['ind_reset'];
if(!isset($pages[$key])) {
//if that posted value isn't a key in the array, it's bad
error_log('Invalid posted page'.$key);
} else {
//this is a valid posted page
$ind_reset = $pages[$key];
//** do the database stuff right here in this spot **//
}
Now, for the reason your posted code doesn't work, you are missing the final, crucial part of doing a database query: the part where you actually run the query.
$conn = mysql_connect("server", "username", "password") or error_log(mysql_error());
mysql_select_db("database") or error_log(mysql_error());
$sql = 'UPDATE counters SET Hits =\'0\' WHERE Page = \'$ind_reset\';';
mysql_query($sql, $conn) or error_log(mysql_error());
I hope you have noted that I replaced "die" with "error_log." If you do error_log(mysql_error(), 1, 'youremail#example.com'), it will email it to you. Otherwise, as with in my examples, it gets put into wherever your system's error log file is. You can then have a nice history of your database errors so that, when you inevitably return to StackOverflow with more questions, you can tell us exactly what's been going on. If you use a file, just make sure to either rotate the error log file's name (I name them according to the day's date) or clear it out regularly, or it can get really, really long.
Using the mysqli code you posted in your comment is a better idea than the mysql_* functions, but you don't quite have it correct. The "bind_param" part sticks your variable into the spot where the question mark is. If your variable is a string, you put "s" first, or if it's an integer, you put "i" first, etc. And make sure you close things once you're done with them.
$db = new mysqli("server", "username", "password", "database");
if(!$db->connect_errno) {
$stmt = $db->prepare("UPDATE counters SET Hits = '0' where Page = ?");
$stmt->bind_param('s',$ind_reset); //assuming $ind_reset is a string
if(!$stmt->execute()) {
error_log($stmt->error);
}
$stmt->close();
} else {
error_log($db->connect_error);
}
$db->close();
This is driving me nuts. I am using the jQuery image upload and crop from
http://www.webmotionuk.co.uk/php-jquery-image-upload-and-crop/
I am using a modified version of the suggestion on here to store the file location in a MySQL database. The mod is that I use INSERT on a table it works great except one thing, the 'owner' variable $id is being stored as $id and not as the value of $id. I can echo the value if $id on each $_POST so I know it's there.
I am pretty sure my syntax is correct but I don't understand why it is doing this.
$cropped = resizeThumbnailImage($thumb_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
//connect to the database
include 'config.php';
// check connection
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
$sql = "INSERT INTO `photos` (`id`,`owner`,`url`) VALUES ('id','".$id."','".$thumb_image_location."')";
// Performs the $sql query on the server to insert the values
if ($conn->query($sql) === TRUE) {
$conn->close();}
//Reload the page again to view the thumbnail
header("location:".$_SERVER["PHP_SELF"]);
exit();
The first line is 246 and the last 3 are the orginal 247-250.
Thanks for any help you can provide.
Ok, I don't know if this is my brain fart or an issue with PHP or a bit of both. I have $id assigned from the _SESSION variable in the header of each page AND (having forgotten that) I was passing $id as _POST data (same value). Once I cut out the _POST data passing and just pulled the _SESSION variable it works fine. But assigning a variable multiple times shouldn't be an issue, should it?
the query line needs to be like this:
$sql = "INSERT INTO `photos` (`id`,`owner`,`url`) VALUES ('id','$id','$thumb_image_location')";
your syntax works fine too, as seen here
this is how my syntax works, here
Note: both work the same, so still trying to figure out what's wrong in OP's code.