I'm very new to PHP and am having some trouble. I have a form using HTML which is action=.php method=post
The form is using text boxes and select options, I'm not sure if it makes a difference in sqldatabase. I've tried about 30 different combinations of this script and can only get a connect successfully message but nothing is posted.
<?php
$link = mysql_connect('everybodyslistcom.ipagemysql.com', 'accounts', 'accounts');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db("user");
$FName = $_POST["FName"];
$LName = $_POST["Lname"];
$Phone = $_POST["Phone"];
$EmailAddress = $_POST["EmailAddress"];
$Month = $_POST["Month"];
$Day = $_POST["Day"];
$Year = $_POST["Year"];
$Username = $_POST["Username"];
$Password = $_POST["Password"];
$sql = 'INSERT INTO Members (ID, FName, LName, Phone, EmailAddress, Month, Day, Year, Username, Password) VALUES'
. '(\'\', \'$FName\', \'$LName\', \'$Phone\', \'$EmailAddress\', \'$Month\', \'$Day\', \'$Year\', \'$Username\', \'$Password\')';
mysql_close();
php?>
try to execute your query
mysql_query($sql);
EDIT: I see you are doing this:
$sql = 'SELECT bla bal $variable';
PHP will not parse the variable. The right way:
$sql = "SELECT bla bla $variable"; // valid
$sql = "SELECT bla bla {$variable}"; // also valid
$sql = 'SELECT bla bla '.$variable; // also valid
your closing php tag is not correct, it should be
?>
rather than
php?>
Also u r not executing your query using:
mysql_query('your query here');
this might cause the problem.
Your variables are not interpreted by PHP. If you want variable to be parsed in string, it should be wrapped in double-quote (")
It may fail if any of your posted data contains some quote character, so you must apply mysql_real_escape_string to all of them.
I hope that database connection credentials are not real you posted here? :D
You said that your form contains "action=.php" literally, you have to turn it into :
<form name="form_name" method="post" action="your_script.php">
You need to execute the query too:
mysql_query($sql, $link);
you should also check whether POST was really sent:
if (!empty($_POST)) {
// ... your code here
}
next thing: you don't need closing tag ?> if your *.php file consist only PHP code - end of file is also correct end of PHP block of code - it's "good-to-have" habit, because in some cases it helps you to avoid error: "Cannot add/modify header information - headers already sent by..."
next problem - wrong way of inserting variables into string:
$sql = 'INSERT INTO Members (ID, FName, LName, Phone, EmailAddress, Month, Day, Year, Username, Password) VALUES'
. '(\'\', \'$FName\', \'$LName\', \'$Phone\', \'$EmailAddress\', \'$Month\', \'$Day\', \'$Year\', \'$Username\', \'$Password\')';
correct way:
$sql = "INSERT INTO Members (ID, FName, LName, Phone, EmailAddress, Month, Day, Year, Username, Password) VALUES (null, '$FName', '$LName', '$Phone', '$EmailAddress', '$Month', '$Day', '$Year', '$Username', '$Password')";
more info here
next - as Deniss said, instead of:
$FName = $_POST["FName"];
should be:
$FName = mysql_real_escape_string($_POST["FName"]);
actually you should fist check weather magic quotes gpc are on or off:
if (get_magic_quotes_gpc()) {
if (!empty($_POST)) {
array_walk_recursive($_POST, 'stripslashes_value');
}
}
function stripslashes_value(&$value) {
$value = stripslashes($value);
}
without this you could have problem with double \\ inserted into db (it depends on your server configuration)
and last but not least: as Robert said you miss one more important thing:
mysql_query($sql);
I think your error because your have not call mysql_query function
can try my code edit
<?php
$link = mysql_connect('everybodyslistcom.ipagemysql.com', 'accounts', 'accounts');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db("user",$link);
$FName = $_POST["FName"];
$LName = $_POST["Lname"];
$Phone = $_POST["Phone"];
$EmailAddress = $_POST["EmailAddress"];
$Month = $_POST["Month"];
$Day = $_POST["Day"];
$Year = $_POST["Year"];
$Username = $_POST["Username"];
$Password = $_POST["Password"];
$sql = "INSERT INTO Members SET FName='{$FName}', LName='{$LName}', Phone='{$Phone}', EmailAddress='{$EmailAddress}', Month='{$Month}', Day='{$Day}', Year='{$Year}', Username='{$Username}', Password='{$Password}'";
// Call Function mysql_query insert new record in mysql table
mysql_query($sql,$link);
mysql_close($link);
?>
Comment for me if your have problem :) or notes of apache services
good day
Related
I would like to add comments to a database using a simple form. For whatever reason, I can't seem to get the table to update when I use said form. I'm not getting any errors, it's just that nothing happens when I refresh the table afterwards. In other words, even after submitting the form, the table still has 0 entries. Here is my code:
<?php
session_start();
$connection = mysql_connect("server", "username", "password");
if ($connection->connect_error) {
die('Connect Error: ' . $connection->connect_error);
}
// Selecting Database
mysql_select_db("database", $connection) or die(mysql_error());
$name = $_POST['name'];
$title = $_POST['title'];
$comments = $_POST['comments'];
$sql = "INSERT INTO comments (Name, Title, Comments)
VALUES ('$name', '$title', '$comments')";
mysql_close($connection); // Closing Connection
?>
Thank you for your help!
You don't ever actually execute your query:
$sql = "INSERT INTO comments (Name, Title, Comments)
VALUES ('$name', '$title', '$comments')";
$result = mysql_query($sql);
Other things:
if ($connection->connect_error) { is not valid. You can't use the old mysql API in an OOP fashion. You need to use mysqli for that.
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
You are also wide open to SQL injections
You do no error checking. How do you expect to know if there are problems if you don't look for them?
(note: please change server, username, and password for your server information)
<?php
session_start();
$connection = mysql_connect("server","username","password");
if (!$connection) {
die('Connect Error: ' . mysql_error());
}
// Selecting Database
mysql_select_db("database",$connection) or die(mysql_error());
$name = $_POST['name'];
$title = $_POST['title'];
$comments = $_POST['comments'];
$sql = "INSERT INTO comments (Name,Title,Comments)
VALUES ('$name', '$title', '$comments')";
mysql_query($sql);
mysql_close($connection); // Closing Connection
?>
For security (defense against SQL injection) you can using mysql_real_escape_string function for limit input fields. For example:
$name = mysql_real_escape_string($_POST['name']);
$title = mysql_real_escape_string($_POST['title']);
$comments = mysql_real_escape_string($_POST['comments']);
I've been tinkering with my PHP code to insert data into a SQL table and I always get ERROR QUERYING DATABASE. The values are coming from a normal HTML form and and then when I hit submit (action=memberadd.php) I get the error message from the code below. I'm missing something but can't see what it is????
<?php
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$city = $_POST['city'];
$state = $_POST['state'];
$country = $_POST['country'];
$industry = $_POST['industry'];//only showing one - need to fix
$profile_visibility = $_POST['profile_visibility'];
$position = $_POST['position'];
$status = $_POST['status'];
$profile_link = $_POST['profile_link'];
$skills = $_POST['skills'];
//connects and sends information to the database
$dbc = mysqli_connect('localhost', 'root', 'root', 'main') or die('Error connecting to MySQL server.');
//inserts data into the member_details table main db
$query = "INSERT INTO 'member_details' (first_name, last_name, city, state, country, industry, profile_visibility, position, status, profile_link, skills)
VALUES ('$first_name', '$last_name', '$city', '$state', '$country', '$industry', '$profile_visibility', '$position', '$status', '$profile_link', '$skills')";
$result = mysqli_query($dbc, $query) or die('Error querying database.');
mysqli_close($dbc);
echo '<h2>Here are your details.</h2>';
echo '<h3>First Name: '.$first_name.'<br />';
echo '<h3>Last Name: '.$last_name.'<br />';
echo 'City: '.$city.'<br />';
echo 'State: '.$state.'<br />';
echo 'Country: '.$country.'<br />';
echo 'Industry: '.$industry.'<br />';//only showing one - need to fix
echo 'Profile: '.$profile_visibility.'<br />';
echo 'Position: '.$position.'<br />';
echo 'Status: '.$status.'<br />';
echo 'Link: '.$profile_link.'<br />';
echo 'Skills: '.$skills.'<br /></h3>';
?>
The Problem
As #Fred -ii- has noted the problem is with the quotes being around the table name in your INSERT statement.
$query = "INSERT INTO 'member_details' (first_name, ...
^ ^
The solution
If you wish to 'quote' table or column names, you should use backticks which you can read more about on the MySQL documentation page.
$query = "INSERT INTO `member_details` (first_name, ...
Detecting errors
To check a MySQLi database request for errors there are a few methods that can be used to get error information. Probably the most useful is mysqli_error() which will give you an error string.
$result = mysqli_query($dbc, $query);
if(!$result)
{
printf("Errormessage: %s\n", mysqli_error($dbc));
}
As #Fred -ii- also mentioned you should use error reporting correctly when developing new code. Ideally you should configure this in your php.ini, but it can also easily be done by adding the following to the top of your page(s).
error_reporting(E_ALL);
ini_set('display_errors', 1);
Finally, you're wide open to SQL Injection Attacks. You should look into using prepared statements with MySQLi to help prevent this.
You can use mysql query like...
$query = "INSERT INTO `member_details` SET first_name = '".$first_name."', last_name = '".$last_name."', city = '".$city."', state = '".$state."', country = '".$country."', industry = '".$industry."', profile_visibility = '".$profile_visibility."', position = '".$position."', status = '".$status."', profile_link = '".$profile_link."', skills = '".$skills."'";
I cannot find any syntax errors for the life of me so I don't understand why the data is not being inserted into my database. When I run the script in my browser with text instead of variables and no if statement I get a successful connection but It doesn't insert the data into mysql. Its driving me nuts! Thanks in advance.
PHP:
<?php
// Establish secure connection
$link = mysql_connect('myserver', 'myuser', 'mypass');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db(events_60);
if ($_POST['requester'] == "NewSale") {
$FirstName = $_POST['First_Name'];
$LastName = $_POST['Last_Name'];
$Birthday = $_POST['UserBirthday'];
$PhoneNumber = $_POST['PhoneNo'];
$Email = $_POST['UserEmail'];
mysql_query($link, "INSERT INTO events_60 (LastName, FirstName, Birthday, Phone, email)
VALUES('$LastName', '$FirstName',' $Birthday', '$PhoneNumber', '$Email')")
or die ("SYSTEM FAILURE");
echo 'System Updated';
} // close first if for post
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// close mysql connection
mysql_close();
?>
Assuming all data is posting correctly to the webpage I think the error resides here:
mysql_select_db(events_60);
It should be:
mysql_select_db('events_60', $link);
http://www.php.net/manual/en/function.mysql-select-db.php
First of all select_db query should be
mysql_select_db('events_60',$link);
Then second problem is in mysql_query. It should be like this:
mysql_query("INSERT INTO events_60 (LastName, FirstName, Birthday, Phone, email)
VALUES('$LastName', '$FirstName',' $Birthday', '$PhoneNumber', '$Email')",$link)
or die ("SYSTEM FAILURE");
$link identifier should come after query.
Hope that fixes it. :)
I have almost no experience with PHP and right now I'm stuck at the total beginning, which is really frustrating. I have a code, which seems to work. From my app I can input values and put them in my PHP database. Thing is that he only inputs the very last value from my PHP code. So the app aside: If I only use the PHP code to input something in my database he always only takes the last value. Here is my code:
<?php
$DB_HostName = "localhost";
$DB_Name = "xxx";
$DB_User = "xxx";
$DB_Pass = "xxx";
$DB_Table = "contacts";
if (isset ($_GET["name"]))
$name = $_GET["name"];
else
$name = "Blade";
if (isset ($_GET["lastname"]))
$lastname = $_GET["lastname"];
else
$lastname = "Xcoder";
if (isset ($_GET["number"]))
$number = $_GET["number"];
else
$number = "111";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
$sql = "insert into $DB_Table (Firtname) values('$name');";
$sql = "insert into $DB_Table (Lastname) values('$lastname');";
$sql = "insert into $DB_Table (Number) values('$number');";
$res = mysql_query($sql,$con) or die(mysql_error());
mysql_close($con);
if ($res) {
echo "success";
}else{
echo "faild";
}// end else
?>
To clarify: If I only have the firstname value, he inputs it in the right place (firstname). If I have a firstname and lastname value, he only inputs the lastname value, but not the firstname value (still at the right place lastname). And the same for number. If I have a firstname, lastname and a number, he only puts the number in the right place but not the other values. In addition I can only do it once. If I want to enter another contact he always says (Duplicate entry 'myentry' for key 'PRIMARY').
You overwrite your query, 2 ways to solve. Either 3 different variables, or 1 variable with 3 queries in it. I would prefer the 2nd option
$sql = "insert into $DB_Table (Firtname) values('$name');";
$sql .= "insert into $DB_Table (Lastname) values('$lastname');";
$sql .= "insert into $DB_Table (Number) values('$number');";
$res = mysql_query($sql,$con) or die(mysql_error());
Or if it can be 1 row in the table, as it is the same table anyways:
$sql = "insert into $DB_Table (Firtname,Lastname,Number) values('$name','$lastname','$number');";
$res = mysql_query($sql,$con) or die(mysql_error());
Because you are overwriting $sql on the next 2 lines, so the final sql line is what is inserted.
Your sql is wrong if you want them all in the same row.
$sql = "insert into $DB_Table (Firtname,lastname,number) values('$name','$lastname','$number');";
You are overwriting your $sql statements. You have to execute them. By doing:
$sql = "Insert INTO..."
you merely set a a variable. You need to ru each query using mysql_query().
I'm also guessing that you want to do this:
$sql = "INSERT INTO $DB_TABLE (Firstname, Lastname, Number) VALUES ('$name', '$lastname', '$number')
Finally, it is crucial that you sanitise your inputs:
$name = mysql_real_escape_string($_GET["name"]);
Thanks to this you avoid an SQL Injection attack.
You are overwriting $sql string each time.
Perhaps you meant to use the .= to append all three queries together. What is the structure for database tables?
$sql = "insert into $DB_Table (Firtname) values('$name');";
$sql .= "insert into $DB_Table (Lastname) values('$lastname');";
$sql .= "insert into $DB_Table (Number) values('$number');";
That is because you use the same variable name ($sql) for all 3 queries. Use $sql1, $sql2 and $sql3 instead. Also, call mysql_query for each one (but only if you've set it).
Like this:
$sql1 = "insert into $DB_Table (Firtname) values('$name');";
$sql2 = "insert into $DB_Table (Lastname) values('$lastname');";
$sql3 = "insert into $DB_Table (Number) values('$number');";
if (isset ($sql1))
{
$res1 = mysql_query($sql1,$con) or die(mysql_error());
}
if (isset ($sql2))
{
$res2 = mysql_query($sql2,$con) or die(mysql_error());
}
if (isset ($sql3))
{
$res3 = mysql_query($sql3,$con) or die(mysql_error());
}
i'm writing a php code to insert form values in a forum values
$dbServer = mysql_connect("localhost" , "root", "") ;
if(!$dbServer) die ("Unable to connect");
mysql_select_db("kfumWonder");
$name= $_POST['name'] ;
$password= md5($_POST['password']);
$email= $_POST['email'] ;
$major= $_POST['major'] ;
$dateOfBirth=$_POST['dateOfBirth'] ;
$webSite = $_POST['website'];
$joinDate= date("Y m d") ;
$query = "INSERT INTO user (name, password, email, major, dob, website, join_date)
Values ('$name', '$password', '$email', '$major', '$dateOfBirth',
'$webSite' , '$joinDate')" ;
//echo $query ;
$result = mysql_query($query) ;
if (! $result )
echo " no results " ;
this works perfectly fine when i took the printed query and run it in PHPMyAdmin but when i run this code nothing happens
Your POST vars need to be escaped if you do not have magic quotes on like this mysql_real_escape_string($_POST['blah']). Even if magic quotes is on, you should strip slashes, or turn off magic quotes in the cofig, and re-escape them with mysql_real_escape_string. Or use PDO to do database entries as it handles this for you.
Also, to see what your errors are, you could call your query like this:
if (!$result = mysql_query($query)) echo mysql_error();