sql update error using php - php

I keep getting
Server error
The website encountered an error while retrieving https://www.website.com/update.php?FName=asdd&PHONE=4444444444. It may be down for maintenance or configured incorrectly.
<?php
$FName = $_POST['FName'];
$LName = $_POST['LName'];
$PHON = $_POST['PHON'];
//connect
$dbh=mysql_connect ("localhost", "username", "password") or die ('ERROR!');
mysql_select_db ("user_Client");
$query = "INSERT INTO ClientTable (ID, FName, LName, PHON) VALUES
('NULL','".$FName."','".$LName."','".$PHON."')";
mysql_query($query) or die ('Error updating Daatabase');
echo "Database Update with:" .$FName. " " .$LName. " " .$PHON. ;
?>
I don't know what's the problem here. I followed instructions from here http://teamtutorials.com/web-development-tutorials/php-tutorials/inserting-data-into-a-mysql-database-using-php#.UEiSQY3iajk
If it helps - I'm using cPanel from Josthost.
Here is the form:
<html>
<head>
<title></title>
</head>
<body>
<form method="post" action="update.php">
First Name:<br/>
<input type="text" name="FName" size="30" /><br/>
Last Name:<br/>
<input type="text" name="LName" size="30" /><br/>
Phone:<br/>
<input type="text" name="PHON" size="12" /><br/>
<input type="submit" value="Update Database"/>
</form>
</body>
</html>

Please use PDO because mysql_* functions are deprecated ..
For your problem, you use $_GET and not $_POST, also you misspelled your variables ($FNLame):
$db = new PDO('mysql:host=localhost;dbname=user_Client;charset=UTF-8', 'username', 'password', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$FName = $_GET['FName'];
$LName = $_GET['LName'];
$PHON = $_GET['PHON'];
$stmt = $db->prepare("INSERT INTO `ClientTable`(ID, FName, LName, PHON) VALUES (0,:FName,:LName,:PHON)");
$stmt->execute(array(':FName' => $FName, ':LName' => $LName, ':PHON' => $PHON));
echo "Database Update with:" .$FName. " " .$LName. " " .$PHON;

Your last statement is wrong:
echo "Database Update with:" .$FName. " " .$LName. " " .$PHON. ;
Should be (without the last dot):
echo "Database Update with:" .$FName. " " .$LName. " " .$PHON ;
If you look in the error log of your webserver, you'll be able to see the error. Another idea could be to turn on errors in PHP in either php.ini or with ini_set("display_errors", 1);. Make sure you only do that on your development system though.

you are checking $_POST['PHON'], while in Query string you are passing
https://www.website.com/update.php?FName=asdd&PHONE=4444444444.
Please correct PHONE first. then check
and get it like
$_GET['PHONE']
or
$_REQUEST['PHONE']

May be sql error due to quotes (' or ""). To avoid this, you can use something like
$FName = mysql_real_escape_string($_POST['FName']);
$FNLame = mysql_real_escape_string($_POST['FLame']);
$PHON = $_POST['PHON'];

is your username and password correct? default for the majority of localhost is root and no password

Related

Can't send query to db

im trying out some code by my own. I just started to learn PHP & mysql. Could anyone tell me where is the mistake? I got a error when processing the query.
My db is set like in the code.
Db name: sweepstakes
Table name: alfa
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "sweepstakes";
$db = mysqli_connect($dbhost,$dbuser,$dbpass, $dbname);
if(mysqli_connect_errno()){
die("Database connection failed: " .
mysqli_connect_errno() .
" (" . mysqli_connect_errno() . ")"
);
}
if($_SERVER['REQUEST_METHOD']=='POST'
&& $_POST['submit']=='Submit'
&& !empty($_POST['name'])
&& !empty($_POST['description'])
&& !empty($_POST['adress'])) {
$name = $_POST['name'];
$desc = $_POST['description'];
$adress = $_POST['adress'];
$query = "INSERT INTO alfa (name, description, adress) VALUES ('$name', '$desc', '$adress')";
$result = mysqli_query($db, $query);
if($result){
}else{
die("Database query failed." . mysql_error() . " " . mysqli_connect_error($db));
}
} else { echo "Empty!";
}
?>
<form method="post" action="index.php">
<fieldset>
<legend>New Sweepstakes</legend>
<label>Name: </br>
<input type="text" name="name" maxlength="150" />
</label> </br>
<label>Description:</br>
<textarea name="description" cols="45" rows="10"></textarea>
</label> </br>
<label>Adress:</br>
<input type="text" name="adress" maxlength="1080" />
</label> </br>
<input type="submit" name="submit" value="Submit" />
</fieldset>
</form>
You're mixing mysql and mysqli functions. Stick with mysqli, mysql is deprecated (don't use it).
In case you didn't spot it: mysql_error() should be mysqli_error()
In addition to checking what Halcyon writes ( using mysqli_error() ), I would also check the query string itself. Just echo out $query right after it's built (the $query = "INSERT..." line) and when running the script look to see if the output matches what you expect to happen, ie that you see something like INSERT INTO alfa (name, description, adress) VALUES ('fred', 'blonde dude', 'Anywhere 32B'). If anything looks out of place (like maybe you have a ' or " in the inputed data and it's screwing up the string output), fix it and try again.
echo and print and print_r()are your friends when doing detective work on new code to see what is the output expected.
(edit)
After reading your update with Halcyon, you should probably check how your auto-incremented field is set up. If, for example, you've been tinkering with this for a while but only set the auto-increment field to INT(2), you might have run out of space for numbers (can only go up to 99 with INT(2)). Increase it to INT(11) or something similar, empty the table, and try again. You can also try ALTER TABLEtable_nameAUTO_INCREMENT = 1 to reset the auto numbering.

Submitting form, mysql and php

I'm new to php and sql and all that stuff, and I was watching a tutorial on youtube about forums in php and wonder why this code doesn't echo "Success" when submitting the form. I also wonder why it echo out Failure before I have submitted the form. I have connected successfully to the database.
<!DOCTYPE HTML>
<html>
<head>
<title>Register</title>
</head>
<body>
<form action="register.php" method="POST">
Username: <input type="text" name="username">
<br/>
Password: <input type="password" name="password">
<br/>
Confirm Password: <input type="password" name="confirmPassword">
<br/>
Email: <input type="text" name="email">
<br/>
<input type="submit" name="submit" value="Register"> or Log in
</form>
</body>
</html>
<?php
require('connect.php');
$username = $_POST['username'];
$password = $_POST['password'];
$confirmPassword = $_POST['confirmPassword'];
$email = $_POST['email'];
if(isset($_POST["submit"])){
if($query = mysql_query("INSERT INTO users ('id', 'username', 'password', 'email') VALUES('', '".$username."', '".$password."', '".$email."')")){
echo "Success";
}else{
echo "Failure" . mysql_error();
}
}
?>
Connect.php
<?php
$connect = mysqli_connect("localhost", "root", "") or die("Could not connect to server!");
mysqli_select_db($connect, "php_forum") or die("Could not connect to database!");
?>
There are a few things wrong here.
You're using the wrong identifiers for your columns in (and being quotes):
('id', 'username', 'password', 'email')
remove them
(id, username, password, email)
or use backticks
(`id`, `username`, `password`, `email`)
mysql_error() should have thrown you an error, but it didn't because of:
You're mixing MySQL APIs with mysqli_ to connect with, then mysql_ in your query.
Those two different APIs do not intermix with each other.
Use mysqli_ exclusively and change your present query to:
if($query = mysqli_query($connect, "INSERT...
and change mysql_error() to mysqli_error($connect)
as a rewrite for that block:
if(isset($_POST["submit"])){
if($query = mysqli_query($connect,"INSERT INTO users ('id', 'username', 'password', 'email') VALUES('', '".$username."', '".$password."', '".$email."')")){
echo "Success";
}else{
echo "Failure" . mysqli_error($connect);
}
}
Just to test the error, make the changes as I outlined just above, while keeping the quotes around your columns the way you have it now. You will then see the error that MySQL will throw. You can then do as I've already outlined above and remove the quotes around the column names, or replace them with backticks.
The tutorial you saw may very well used backticks, but were probably not distinguishable enough for you to tell that they were indeed backticks and not single quotes.
However, your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
I noticed you may be storing passwords in plain text. If this is the case, it is highly discouraged.
I recommend you use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
Also, instead of doing:
$connect = mysqli_connect("localhost", "root", "") or die("Could not connect to server!");
mysqli_select_db($connect, "php_forum") or die("Could not connect to database!");
You should be checking for errors instead, just as the manual states
$link = mysqli_connect("myhost","myuser","mypassw","mybd")
or die("Error " . mysqli_error($link));
http://php.net/manual/en/function.mysqli-connect.php
So in your case:
$connect = mysqli_connect("localhost", "root", "","php_forum")
or die("Error " . mysqli_error($connect));
Edit: and I changed action="register.php" to action="" since you're using the entire code inside the same page.
<!DOCTYPE HTML>
<html>
<head>
<title>Register</title>
</head>
<body>
<form action="" method="POST">
Username: <input type="text" name="username">
<br/>
Password: <input type="password" name="password">
<br/>
Confirm Password: <input type="password" name="confirmPassword">
<br/>
Email: <input type="text" name="email">
<br/>
<input type="submit" name="submit" value="Register"> or Log in
</form>
</body>
</html>
<?php
require('connect.php');
$username = $_POST['username'];
$password = $_POST['password'];
$confirmPassword = $_POST['confirmPassword'];
$email = $_POST['email'];
if(isset($_POST["submit"])){
if($query = mysqli_query($connect,"INSERT INTO users (`id`, `username`, `password`, `email`) VALUES ('', '".$username."', '".$password."', '".$email."')")){
echo "Success";
}else{
echo "Failure" . mysqli_error($connect);
}
}
?>
:It will echo ;Failure' so executing this bit of code
else{
echo "Failure" . mysql_error();
}
whenever $_POST["submit"]) is not set and it will be not set anytime you open you page (even if you navigate to it from your bookmark of from google search results) or when you submit you FORM in GET mode

I cannot insert records into Database using HTML Form and PHP

No records show up in my MyPHP Database when I run these scripts.
I am running:
APACHE 2.4.7
MYSQL 5.6.15
PHP 5.5.8
First the HTML Code...
<html>
<center>
<font face="Helvetica">
<u><b>Matthew Gieger's Guestbook</b></u>
<form action="link.php" method="post"/>
<p>Name: </p>
<input type="text" name="Name" required/>
<p>Email: </p>
<input type="email" name="Email" required />
<p>Message: </p>
<p><textarea rows="4" cols="50" name="Message"> </textarea></p>
<input type="submit" value="Submit" />
<input type="reset" value="Reset" />
</form>
</center>
</html>
And the PHP Script. This is where I think the problem is...
<?php
$username='root';
$password='';
$database='guestbook';
$name= $_POST['Name'];
$email= $_POST['Email'];
$message= $_POST['Message'];
new mysqli('localhost',$username,$password,$database) or die("could not connect to localhost");
echo"connected";
mysqli:"insert into contacts (Name,Email,Message,Timestamp) values ($name,$email,$message,date())";
?>
I get no error when I run the code. I just get the expected
"connected"
You don't have a mysqli object defined anywhere. And you're not using mysqli_query() anywhere.
Here are the docs to mysqli.
Try something like this:
$mysqli = new mysqli('localhost', $username, $password, $database);
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$mysqli->query("INSERT INTO `contacts`(`Name`, `Email`, `Message`, `Timestamp`) VALUES ('". $name ."', '". $email ."', '". $message ."', '". $timestamp ."')");
You're not instantiating the mysqli class properly. You need to save the object instance into a variable:
$mysqli = new mysqli('localhost',$username,$password,$database);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
There's also a serious security issue in your code, since you're not escaping your input variables. Best solution would be to look into PDO: http://php.net/manual/en/pdo.construct.php and parameter binding.
If you really want to do this with mysqli, you should first use mysqli_real_escape_string on all your input variables:
$name = mysqli_real_escape_string($mysqli, $_POST['Name']);
$email = mysqli_real_escape_string($mysqli, $_POST['Email']);
$message = mysqli_real_escape_string($mysqli, $_POST['Message']);
And then run your query properly:
$mysqli->query("insert into contacts (Name,Email,Message,Timestamp) values ('$name','$email','$message',".date().")";
If you don't escape the user input's, it will be really easy to hack your database with a simple SQL injection.
most likely a formatting issue, try it like this:
<?php
$username='root';
$password='';
$database='guestbook';
$name= $_POST['Name'];
$email= $_POST['Email'];
$message= $_POST['Message'];
$db = new mysqli('localhost',$username,$password,$database) or die("could not connect to localhost");
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$currentDate=date();
$sql = "insert into contacts (Name,Email,Message,Timestamp) values ($name,$email,$message,$currentDate)";
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
?>

Storing emails in a MySQL database using an HTML Form and PHP

I am working to make a form where I can collect names and email addresses and send them to a MySQL database for storage. I wrote the HTML and PHP file and it seems to be working. It echoes "Thank you for entering an email!". When I look at the database it creates a line for the data but all the fields are blank. I am not sure what's going on, and this is the first time I have worked with a database. Thanks for all your help!
HTML
<form action='/submitEmail.php' action='POST'>
<p>First name: <input type='text' id="firstname" name='firstname' /></p>
<p>Last name: <input type='text' id="lastname" name='lastname' /></p>
<p>Email: <input type='text' name='email' /></p>
<input type='submit' value='Submit Email' />
</form>
PHP
<?php
// Connecting to the MySQL server
$host="myHost";
$user_name="myUsername";
$pwd="myPassword";
$database_name="myDatabase"; //assuming you created this
$db=mysql_connect($host, $user_name, $pwd);
if (mysql_error() > "") print mysql_error() . "<br>";
mysql_select_db($database_name, $db);
if (mysql_error() > "") print mysql_error() . "<br>";
// Storing form values into PHP variables
$firstname = $_POST["firstname"]; // Since method="post" in the form
$lastname = $_POST["lastname"];
$email = $_POST["email"];
// Inserting these values into the MySQL table
// we created above
$query = "insert into email_list (firstname, lastname, email) values ('" . $firstname . "', '" . $lastname . "', '" . $email . "')";
$result = mysql_query($query);
// mysql_query() is a PHP function for executing
// MySQL queries
echo "<p>Thank you for entering an email!</p>";
?>
Attribute method should be post.
<form action='/submitEmail.php' method='POST'>
You wrote action='POST' instead of method='POST'. Try to use later one. It should work.
Happy coding!!

Form Redirect after Submit to PHP mySQL db

I need to redirect submissions so that users aren't taken to a blank screen.
Here's the code for my form::
<form action="giveaway_execute.php" method="post">
First Name:
<input type="text" name="firstname" /><br />
Last Name:
<input type="text" name="lastname" /><br />
etc...
...
...
<p><input type="submit" value="Submit"/>
</p>
</form>
and here's the php for 'giveaway_execute.php' which interacts with the mySQL db (everything submits; removed password and db name for security)::
<?php
define ( 'DB_NAME','xxxx');
define ( 'DB_USER','xxxx');
define ( 'DB_PASSWORD','xxxx');
define ( 'DB_HOST','localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!link) {
die('Could not connect: ' .mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
}
$value1 = $_POST['firstname'];
$value2 = $_POST['lastname'];
$value3 = $_POST['phone'];
$value4 = $_POST['street'];
$value5 = $_POST['city'];
$value6 = $_POST['state'];
$value7 = $_POST['zip'];
$value8 = $_POST['email'];
$value9 = $_POST['weddingdate'];
$sql = "INSERT INTO entrants (firstname, lastname, phone, street, city, state, zip, email, weddingdate) VALUES ('$value1', '$value2', '$value3', '$value4', '$value5', '$value6', '$value7', '$value8', '$value9')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
mysql_close();
?>
I've tried redirects on the PHP file but nothing is working. Any suggestions would be greatly appreciated.
Thank you.
You can just include another page after you're done with your database operations, or as suggested you can use a header call but be sure to use an absolute url.
Also worth noting your code is highly vulnerable to SQL injection, and it doesn't do any validation.
It's a good idea to use isset on your fields to avoid getting notices and SQL errors if fields aren't set.
Finally, it's recommended to use a library such as PDO or mysqli over the older mysql_* extension.
try
header('location:page2.php');
at the end of the file.
Replace page2.php with the actual page you want to send them to
// process.php
$db = new PDO('mysql:host=localhost;dbname=test', 'root', 'root');
if(isset($_POST['value'])){
error_log(print_r($_POST,1),0);
$db->query('INSERT INTO test (id, value) VALUES (NULL, "'.$_POST['value'].'")');
header('Location: http://google.com');
exit();
}
else {
echo "$_POST is not set.";
}
// form.php
<form action="process.php" method="post">
<input type="text" name="value">
<input type="submit" id="submit-btn" value="Submit">
</form>
Try something simpler and build from there. Also read this: http://www.php.net/manual/en/pdo.prepared-statements.php

Categories