I am developing a web application that allows a user to add entries to a MySQL database through a web form. The web form posts to the same page, some PHP code captures that data and sends it to MySQL. For whatever reason, nothing ever makes it to MySQL. This is the code I have so far that isn't working:
<?php
include("config.inc.php");
$Name=$_POST['AddName'];
$Group=$_POST['AddGroup'];
$Grade=$_POST['AddGrade'];
$Position=$_POST['AddPosition'];
$Email=$_POST['AddEmail'];
$HomeAddress=$_POST['AddHomeAddress'];
$City=$_POST['AddCity'];
$State="SC";
$Zip=$_POST['AddZIP'];
$CellPhone=$_POST['AddCellNumber'];
$HomePhone=$_POST['AddHomeNumber'];
$FirstPeriod=$_POST['AddFirstPeriod'];
$SecondPeriod=$_POST['AddSecondPeriod'];
$ThirdPeriod=$_POST['AddThirdPeriod'];
$FourthPeriod=$_POST['AddFourthPeriod'];
$FifthPeriod=$_POST['AddFifthPeriod'];
$SixthPeriod=$_POST['AddSixthPeriod'];
$SeventhPeriod=$_POST['AddSeventhPeriod'];
$Homeroom=$_POST['AddHomeroom'];
$dbpassword=$_POST['AddPassword'];
$con = mysql_connect("127.0.0.1","$username","******");
if (!$con)
{
die();
}
mysql_select_db("$database", $con);
$sql="INSERT INTO names (Name,Grp,Grade,Position,Email,HomeAddress,City,State,Zip,CellPhone,HomePhone,FirstPeriod,SecondPeriod,ThirdPeriod,FourthPeriod,FifthPeriod,SixthPeriod,SeventhPeriod,Homeroom)
VALUES('$Name','$Group','$Grade','$Position','$Email','$HomeAddress,'$City','$State','$Zip','$CellPhone','$HomePhone','$FirstPeriod','$SecondPeriod','$ThirdPeriod','$FourthPeriod','$FifthPeriod','$SixthPeriod','$SeventhPeriod','$Homeroom')";
if (!mysql_query($sql,$con))
{
die();
}
echo "1 record added";
mysql_close($con)
?>
</body>
</html>
Try this and see what it says:
if (!mysql_query($sql,$con))
{
die(mysql_error());
}
Try inserting echo mysql_error();. This should give you at least a starting place to where your query is incorrect.
mysql_close($con) should have a semi-colon at the end.
check your log for errors.
use mysql_real_escape_string
PHP hides errors. To debug, start by placing these two lines as the first lines within the <?php tag
error_reporting(E_ALL);
ini_set('display_errors', '1');
Also in case the error was in mysql you can do:
print_r(mysql_fetch_array(mysql_query("SHOW WARNINGS", $con)));
or
print_r(mysql_fetch_array(mysql_query("SHOW ERRORS", $con)));
Directly after the mysql query you think may have failed.
die(mysql_error());
will fix it.
Also have a look at escaping. It would be very easy to inject into the current code.
If you are not going to escape (I don't know when you would do that) you might as well use the $_POST rather than assigning to a variable and using the variable.
change your database selection to
mysql_select_db("database name")
or
mysql_select_db($database);
your are trying to select a database named "$database" with a dollar sign as a string, not the name in that variable.
also, use
mysql_real_escape_string($sql) to escape those variables.(avoiding sql injecion) you can find links about it in other comments.
change
$sql="INSERT INTO names (Name,Grp,Grade,Position,Email,HomeAddress,City,State,Zip,CellPhone,HomePhone,FirstPeriod,SecondPeriod,ThirdPeriod,FourthPeriod,FifthPeriod,SixthPeriod,SeventhPeriod,Homeroom)
VALUES('$Name','$Group','$Grade','$Position','$Email','$HomeAddress,'$City','$State','$Zip','$CellPhone','$HomePhone','$FirstPeriod','$SecondPeriod','$ThirdPeriod','$FourthPeriod','$FifthPeriod','$SixthPeriod','$SeventhPeriod','$Homeroom')";
to
$sql="INSERT INTO names (Name,Grp,Grade,Position,Email,HomeAddress,City,State,Zip,CellPhone,HomePhone,FirstPeriod,SecondPeriod,ThirdPeriod,FourthPeriod,FifthPeriod,SixthPeriod,SeventhPeriod,Homeroom)
VALUES('$Name','$Group','$Grade','$Position','$Email','$HomeAddress','$City','$State','$Zip','$CellPhone','$HomePhone','$FirstPeriod','$SecondPeriod','$ThirdPeriod','$FourthPeriod','$FifthPeriod','$SixthPeriod','$SeventhPeriod','$Homeroom')";
Related
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.
This is the code that connects to my SQL database. I'm new with this stuff and it seems to be semi-working but certain features on my website still don't work.
<?php
$con = mysql_connect("localhost","username","password");
$select_db = mysql_select_db('database1',$con);
/*$con = mysql_connect("localhost","username2","password2");
$select_db = mysql_select_db('database2',$con);*/
?>
This is the site in question: http://tmatube.com keep in mind the credentials above are filled in with what the programmer used for testing on his own server... ;) unfortunately I don't have access to him for support anymore.
Anyway, here's my thoughts on how this code needs to be edited maybe someone can chime in and let me know if I'm correct in my assumptions:
<?php
$con = mysql_connect("localhost","username1","password1"); -------------<<< leave this line
$select_db = mysql_select_db('DATABASE_NAME_HERE',$con);
/*$con = mysql_connect("localhost","DB_USERNAME_HERE","DB_PASSWORD_HERE");
$select_db = mysql_select_db('DATABASE_NAME_HERE',$con);*/
?>
Ok - now on to a few problems I noticed...
What does this do? /* code here */? It doesn't work at all if I leave that bit in.
Why is it connecting to database twice? and is it two separate databases?
$select_db = mysql_select_db('DATABASE_NAME_HERE',$con); <<<---- single '
When I tried to see if that line was correct the examples I saw had quotes like this
$select_db = mysql_select_db("DATABASE_NAME_HERE",$con); <<<---- double "
Which one is right?
He didn't leave it out. What he did was leave the database to be connected using the root, which has no password. The other connection (which is commented out) is using another user, rajvivya_video, with a password defined.
In testing it MIGHT be okay to connect to root and leave it without password, but even that is not recommended, since its so easy to work with a user and password defined (besides root).
Here is php mysql connect with mysqli:
<?php
$link = mysqli_connect("myhost","myuser","mypassw","mybd");
?>
No difference here with ' or ". (Anyway use mysqli and you can the wanted db as 4th parameter.) php quotes
/* comment */ is a commented out so the php does not care what is inside so only 2 first rows of are affecting (they are same mysql database on the local machine and 2 different user + password combinations). Comment in general are used to explain the code or removing part of the code with out erasing it. php commenting
I've made this a lot of times but now I can't :(
The insert allways return false but if I execute the same SQL script (taked from the output) it inserts in the database without any problem. I'm connected to the database because some values are fetched from another table.
This is my code:
$query = "INSERT INTO normotensiones(fecha,macropera,pozo,equipo_pmx,equipo_compania,paciente,sexo,edad,id_compania,otra_compania,puesto,ta,tum,ove,coordinador)
VALUES('$fecha','$macropera','$pozo','$equipo_pmx','$equipo_compania','$paciente','$sexo',$edad,$id_compania,'$otra_compania','$puesto','$ta','$tum','$ove','$coordinador')";
if (mysql_query($query,$connection)){
//OK
} else {
$errno = mysql_errno();
$error = mysql_error();
mysql_close($connection);
die("<br />$errno - $error<br /><br />$query");
exit;
}
The output is:
0 -
INSERT INTO normotensiones(fecha,macropera,pozo,equipo_pmx, equipo_compania,paciente,sexo,edad,id_compania, otra_compania,puesto,ta,tum,ove,coordinador)
VALUES('20111001','P. ALEMAN 1739','P. ALEMAN 1715','726', 'WDI 838','SERGIO AYALA','M',33,21, '','','110/70','ROBERTO ELIEL CAMARILLO','VICTOR HUGO RAMIREZ','LIC. PABLO GARCES')
Looks like there are no error, but allways execute the code in the else part of the if instruction. Any idea? Thanks in advance.
I think the issue might be you are missing the mysql_select_db line after the connection.
After the connection with the database is established you need to select a DB. Please make sure you have selected the Database that your desired table resides in.
And you can even use the following snippets to get some useful informated through mysql_errors.
$connection = mysql_connect('localhost', 'root', 'password');
if (!$connection) {
die('<br>Could not connect: ' . mysql_error());
}
if (!mysql_select_db('db_name')) {
die('Could not select database: ' . mysql_error());
}
And try you insert query after these lines of code. All the best.
I agree with the others concerning the column types. INT is one of the only data types that do not require single quotes.
There are two blank strings. There is a possibility that the variables are not defined, and therefore giving you a PHP exception (not even in the MySql yet) but that requires stricter-than-normal exception settings. I would personally look into the $connection variable. Before the SQL query statement, put this and send us the cleaned results:
echo '<pre>'.var_dump($connection, true).'</pre>';
Additionally, on your mysql_connect function call, put
OR die('No connection')
afterwords. Do the same thing with the mysql_select_db function, changing it to 'No DB Select' obviously.
Ultimately, we will need more information. But changing to mysqli is very desirable.
Oh! And make sure the permissions for the user you are connecting as are not changed. Sometimes I find people who connect to PhpMyAdmin using one user account but a different account in their PHP code. This is problematic, and will lead to problems eventually, as you forget the different accounts, at times.
PHP usually works pretty much straight out of the box, but I cannot get this query to work. I am attempting to update a simple record. My code is as follows.
<?php
$customername=mysql_real_escape_string($_POST['customername']);
$contact=mysql_real_escape_string($_POST['contact']);
$customerorder=mysql_real_escape_string($_POST['customerorder']);
$orderplaced=mysql_real_escape_string($_POST['orderplaced']);
$staffmember=mysql_real_escape_string($_POST['staffmember']);
$daterequired=mysql_real_escape_string($_POST['daterequired']);
$status=mysql_real_escape_string($_POST['status']);
$paid=mysql_real_escape_string($_POST['paid']);
$delivery=mysql_real_escape_string($_POST['delivery']);
$ordercontent=mysql_real_escape_string($_POST['ordercontent']);
$orderid=mysql_real_escape_string($_GET['orderid']);
mysql_connect("localhost", "xxxx", "xxxxxxx") or die("Connection Failed");
mysql_select_db("xxxxxx")or die("Connection Failed");
$query = "UPDATE ordermanager_orders SET customername='$customername', contact='$contact', ordernumber='$customerorder', placedby='$orderplaced', requiredby='$daterequired', status=$status', staffmember='$staffmember', paid='paid', delivery='$delivery', ordercontent='$ordercontent' WHERE order='$orderid'";
if(mysql_query($query)){
echo "updated";}
else{
echo "fail";}
?>
The values are being posted or "Getted" from another page. They are definitely coming through as otherwise it comes up with errors. At the moment it simply comes up with 'failed' as per the code.
I have tried numerous variants of code found on the internet, to check if my coding was correct, however I still cannot get it to work.
I wonder if u have tried to print_r your $query to check.
1st. Shift your connection string to the top most.
2nd. status=$status' <<=== less 1 quote
I thought you had to connect to the database before you were able to use mysql_real_escape_string()? Try connecting above all other code.
The status section of the query is also missing a quote mark.
Try changing by adding a comma
status=$status' to status='$status'
And FYI change paid='paid' to paid='$paid' to ensure the correct value is passed
Your error is because of not handling your status update correctly: status=$status' must be status='$status'.
You would have figured this if you'd put a mysql_error() in your 'fail' section.
I have this code:
if(!mysql_connect($host,$user,$passwd)){
die("Hoops, error! ".mysql_error());
}
...no error from here.
if(!mysql_select_db($db,$connect)){
$create_db = "CREATE DATABASE {$db}";
mysql_query($create_db,$connect);
mysql_query("USE DATABASE {$db}",$connect);
}
..."no database selected" error from here.
I would like to select database if it exists and if doesn't then create it and select it.
Why is my code not right?
Thank you in advance
Where are you saving the value returned by mysql_connect()? Don't see it here. I assume $host, $user, $password and $db are properly set ahead of time. But you're passing a param to mysql_select_db that may not be properly set.
$connect = mysql_connect($host,$user,$passwd);
if (!$connect) {
die('Could not connect: ' . mysql_error());
}
if(!mysql_select_db($db,$connect)) ...
Start by checking to see if you can select without the CREATE query first. Try a simple SELECT query to start. If you can connect, select the db, and execute a SELECT query, that's one step. Then try the CREATE query. If that doesn't work, it's almost certainly a matter of permissions.
You might need database create permissions for the user attempting to create the database.
Then you need to operate on a valid connection resource. $connect never looks to be assigned to the connection resource.
Why not simply use the CREATE DATABASE IF NOT EXISTS syntax instead?
Something like this ...
$con = mysql_connect('localhost');
$sql = 'CREATE DATABASE IF NOT EXISTS {$db}';
if (mysql_query($sql, $con)) {
print("success.\n");
} else {
print("Database {$db} creation failed.\n");
}
if(!mysql_select_db($db,$connect)){
print("Database selection failed.\n");
}
You should check the return value of mysql_query() - currently if any of those calls fail you won't know about it:
if(!mysql_select_db($db,$connect)){
if (!mysql_query("CREATE DATABASE $db", $connect)) {
die(mysql_error());
}
if (!mysql_select_db($db, $connect)) {
die(mysql_error());
}
}
Change the line
mysql_query($create_db,$connect);
mysql_query("USE DATABASE {$db}",$connect);
To
mysql_query($create_db,$connect);
mysql_select_db($db);*
and it should work.
you could try w3schools website. They have a very simple and easy to learn tutorial for selecting database. The link is : http://www.w3schools.com/php/php_mysql_select.asp
Hope this help :)
I would like to thank to all of you, however I found fault on my side. This script was in class and one of variables were not defined inside this class. So I'm really sorry.
I don't know how to consider the right answer, but I noticed my mistake after reading Clayton's answer about not properly set parameters, so I guess he is the winner ;)