this code calls the values entered into a form and enters them into a database (or at least it's supposed to) every time the page loads it gives "undefined index" messages, and I am struggling to determine why.
Any help that can be offered to me is greatly appreciated!
<?php
$dbc=mysql_connect('localhost', 'user', '');
mysql_select_db('database', $dbc);
$sqlInsertString = "INSERT INTO band_information (Name, Photo, Bio, City, State, Zipcode, Genre, Link)
VALUES ({$_POST['bandname']}, {$_FILES['bandphoto']['name']}, {$_POST['bandbio']}, {$_POST['bandcity']},
{$_POST['bandstate']}, {$_POST['bandzipcode']}, {$_POST['bandgenre']},{$_POST['bandlink']});";
if($_SERVER['REQUEST_METHOD']=='POST'){
if(move_uploaded_file($_FILES['bandphoto']['tmp_name'], "C:\\HTML\\mgertenbach\\BAND\\photos\\{$_FILES['bandphoto']['name']}") && $mysql_query($sqlinsertString, $dbc)){
print '<p>Thanks for submitting your band!</p>';
} else {
print '<p>Could not submit band because: <br/>' .
mysql_error($dbc) . '</p>';
}
}
Since you are getting values from your <form> , you need to first check whether they are set or not.
You should make use of the isset construct for that. Like this
if(!isset($_POST['bandname'])) // And whichever variables you get from your <form>
{
echo "Band Name was not Provided";
exit;
}
else
{
//.... do your CRUD operations here
}
Secondly, you are using mysql_* functions which will be deprecated soon. Switch to MySQli or PDO instead.
Related
I am creating a sign up page.
My code was working perfectly before on an intranet, but now, 5 years later I must use MySQL i.
What happens is I connect to the database using external PHP file, dblogin.php
<?php
$connection = mysqli_connect('mywebhost','username','password','db');
?>
That bit works fine, as the login system works using this.
Then comes my registration system.
It has been a while since I coded in PHP, mostly working using Wordpress now.
<?php
include 'dblogin.php';
if(isset($_GET['i'])){
if($_GET['i'] == '1'){ //if we want to insert a new user
$tblName="tblUsers";
//Form Values into store
$FirstName=$_POST['firstnamecreate'];
$Surname=$_POST['Surnamecreate'];
$Username=$_POST['UsernameCreate'];
$UserType="stu"; //never mind this, it just seperates admins from standard users
$Email=$_POST['EmailCreate'];
$Password=$_POST['PasswordCreate'];
$ExistingUserVerification = mysqli_query ($connection,"SELECT COUNT(*) as num FROM tblUsers WHERE UserName = $Username");
$UserResults = mysqli_query($connection,$ExistingUserVerification);
if($UserResults[0] == 1){
$CreatedStatus = "$Username already exists in the user database. Please choose a different Username.";
}else{
$sql="INSERT INTO $tblName(UserName, Password, UserType, FirstName, Surname, EmailAddress)VALUES('$Username', '$Password', '$UserType', '$FirstName', '$Surname', '$Email')";
$result=mysqli_query($connection,$sql);
if($result){
$CreatedStatus = "$FirstName, you have registered successfully. Click " . "<a href=Login.php>". "HERE". "</a>" . " to login. " . "<br />"."Please note: Hacking of this site is not permitted.";
}
else {
$CreatedStatus = "Unfortunately $Username was not created successfully. Please check your entry or check whether the user already exists.";
}
}
}
}
?>
The problem i am getting is around the
$ExistingUserVerification = mysqli_query ($connection,"SELECT COUNT(*) as num FROM tblUsers WHERE UserName = $Username");
$UserResults = mysqli_query($connection,$ExistingUserVerification);
part.
I have tried all sorts. With the current format, it results in:
Warning: mysqli_query(): Empty query in /home/trainman/public_html/Register.php on line 26
removing $connection results in it expecting 2 parameters and removing i says depricated.
Any help much appriciated. It has been a while since I last used php so sorry if the code is untidy. The select COUNT (*) checks if there is another user with the same username, if there isnt it will submit form values to the DB
This error is coming from the extremely simple fact that you are sending an empty query to mysqli. The query is empty. It's but an empty string. Nothing.
So just check your variables.
The second parameter to mysqli_query() should be a PHP string contains a legitimate SQL query. Anything else will cause an error.
I'm a non-CIS major taking an intro programming classes for a minor through my university. I've been able to successfully code most of the PHP files I need but have been getting hung up over how to perform two functions within the same document. Hopefully you can help.
Within the website, I want to be able to first use MySQL to check a table, called User (where a user is initially registered by the site) to verify that they are in fact registered and that the credentials they provided are correct, and then execute an query to add them to another table.
I've tried mysqli_multi_query to no avail and am just generally inexperienced and unsure of my options as far as functions go.
I have included the code below but be aware that it is a mess as I've attempted several different things before I decided to get some help
<?php
session_start();
require_once("config.php");
$GroupDesc = $_GET["GroupDesc"];
$LeaderID = $_GET["LeaderID"];
$URL = $_GET["URL"];
$Email=$_GET["Email"];
$con = mysqli_connect("$SERVER","$USERID","$DBPASSWORD","$DATABASE");
$query2= "INSERT INTO FA15_1052_tuf02984.WebsiteGroups (ID, Description, LeaderID, URL, LeaderEmail) VALUES ('$GroupDesc', '$LeaderID', '$URL', '$Email');";
/* Here I want to perform the first query or $query1 which checks if the
user exists in MySQL and the info submitted in form is same */
$query1= "SELECT * from USER where LeaderID = '$ID' and Email = '$Email';";
if ($status = mysqli_query($con, $query1)) {
} else {
print "Some of the data you provided didn't match our records. Please contact the webmaster.".mysqli_error($con)." <br>";
$_SESSION["RegState"]= -11;
$_SESSION["ErrorMsg"]= "Database insertion failed due to inconsistent data: ".mysqli_error($con);
header("Location:../index.php");
die();
}
/* How do I tell the file to move onto the next query, which is $query2?
if ($query2) {
$query = "INSERT INTO FA15_1052_tuf02984.WebsiteGroups (ID, Description, LeaderID, URL, LeaderEmail)
VALUES ('$GroupDesc', '$LeaderUID', '$URL', '$Email');";
} */
} else {
print "Membership update failed. Please contact webmaster.".mysqli_error($con)." <br>";
$_SESSION["RegState"]= -11; // 0: Not Registered, 1: Register, -1: Error
$_SESSION["ErrorMsg"]= "Database Insert failed: ".mysqli_error($con);
header("Location:../index.php");
die();
}
There are a few points where your code can be rearranged to make the logic easier to follow. (Don't worry; this is just stuff that comes with experience.) I'll include some comments within the following code to explain what I've done.
<?php
session_start();
require_once("config.php");
$GroupDesc = $_GET["GroupDesc"];
$LeaderID = $_GET["LeaderID"];
$URL = $_GET["URL"];
$Email=$_GET["Email"];
// mysqli_connect is deprecated; the preferred syntax is
$con = new mysqli("$SERVER","$USERID","$DBPASSWORD","$DATABASE");
$query1= "SELECT * from USER where LeaderID = '$ID' and Email = '$Email';";
$result = mysqli_query($con, $query1);
// I personally prefer the following opening-brace style; I just find it
// easier to read. You can use the other style if you want; just do it
// consistently.
if ($result)
{
$row = mysqli_fetch_assoc($result);
if($row)
{
if (($row['ID'] != $LeaderID) or ($row['Email'] != $Email))
{
// Handle the error first, and exit immediately
print "Some of the data you provided didn't match our records. Please contact the webmaster.".mysqli_error($con)." <br>";
$_SESSION["RegState"]= -11;
$_SESSION["ErrorMsg"]= "Database Insert failed due to inconsistent data: ".mysqli_error($con);
header("Location:../index.php");
die();
}
else
{
// If the query succeeded, fall through to the code that processes it
$query = "INSERT INTO FA15_1052_tuf02984.WebsiteGroups (ID, Description, LeaderID, URL, LeaderEmail)
VALUES ('$GroupDesc', '$LeaderUID', '$URL', '$Email');";
$status = mysqli_query($con, $query);
if ($status)
{
// membership has been updated
$_SESSION["RegState"]=9.5; // 0: Not Registered, 1: Register, -1: Error
$message="This is confirmation that you the group you lead has been added to our database.
Your group's ID in our database is "$GID". Please keep this in your records as you will need it to make changes.
If this was done in error, please contact the webmaster at tuf02984webmaster#website.com";
$headers = 'From: tuf02984webmaster#example.com'."\r\n".
'Reply-To: tuf02984webmaster#example.com'. "\r\n".
'X-Mailer: PHP/' . phpversion();
mail($Email, "You are a group leader!", $message, $headers);
header("Location:../index.php");
// die();
// You only use die() to return from an error state.
// Calling die() creates an entry in the server's error log file.
// For a successful completion, use
return;
}
}
}
}
// If we get here, then something has gone wrong which we haven't already handled
print "Membership update failed. Please contact webmaster.".mysqli_error($con)." <br>";
$_SESSION["RegState"]= -11; // 0: Not Registered, 1: Register, -1: Error
$_SESSION["ErrorMsg"]= "Database Insert failed: ".mysqli_error($con);
header("Location:../index.php");
die();
?>
The basic idiom is: Do something, handle the specific error, handle success, do something else, etc., and finally handle any errors that can come from multiple points. If anything is unclear, just ask and I'll edit into my answer.
I haven't covered prepared statements here. Prepared statements are the preferred way to perform non-trivial queries; they help to resist SQL injection attacks as well as simplify type-matching, quoting and escaping of special characters.
I have written a PHP page with a form on the submit button I set the action to the PHP form page.
<form id="form1" method="post" action="../control_lbs/lbs_trace.php">
The INSERT INTO is basic sql load information to the database.
The problem i have every time I open the page it sends blank information to the rows. Is there away I can prevent this from happening?
$sql = "INSERT INTO lbs_trace_etrack (lbs_msisdn, lbs_req_by, lbs_date_req,
lbs_reason, lbs_station, lbs_cas, lbs_traced_by)
VALUES
('$_POST[lbs_msisdn]','$_POST[lbs_req_by]','$_POST[lbs_date_req]','$_POST[lbs_reason]'
,'$_POST[lbs_station]','$_POST[lbs_cas]','$_POST[lbs_traced_by]')";
The above is my PHP action code
This is the new code and full code I use
if ($con = mysql_connect($host, $username, $password)) {
if ( !empty($_POST["send"])) {
$sql = "INSERT INTO lbs_trace_etrack (lbs_msisdn, lbs_req_by, lbs_date_req, lbs_reason, lbs_station, lbs_cas, lbs_traced_by)
VALUES ('$_POST[lbs_msisdn]','$_POST[lbs_req_by]','$_POST[lbs_date_req]','$_POST[lbs_reason]','$_POST[lbs_station]','$_POST[lbs_cas]','$_POST[lbs_traced_by]')";
if (mysql_query($sql, $con)) {
$insertSuccessful = true;
} else {
echo $sql;
echo "\n" . mysql_error($con);
echo "mysql err no : " . mysql_errno($con);
}
On refresh or page entry it still gives me blank info on Database
You need to use isset() to see if the $_POST variables are set. I've use $_POST in the example below, I suggest you give the submitbutton a name (like example) and use isset($_POST['example']):
if( isset($_POST) ){
$sql = "INSERT INTO lbs_trace_etrack (lbs_msisdn, lbs_req_by, lbs_date_req, lbs_reason, lbs_station, lbs_cas, lbs_traced_by)
VALUES(
'".$_POST['lbs_msisdn']."',
'".$_POST['lbs_req_by']."',
'".$_POST['lbs_date_req']."',
'".$_POST['lbs_reason']."',
'".$_POST['lbs_station']."',
'".$_POST['lbs_cas']."',
'".$_POST['lbs_traced_by']."'
)";
echo $sql; // echo it to see if it has any values
// print_r($_POST); // in case the query is still empty, uncomment this. It will show you the values in the POST array
}
I'm just using PDO to insert customers into my table but it has been overcomplicated by something which is unexplainable by myself or other research.
It gives the error code: 00000 (which means that is a success, apparently) but no data was actually inserted into the database and the error is only supposed to be outputted if the query was a failure, but the error is.. success?
$insertUser = $database->prepare("INSERT INTO customer (Surname, Forename, AddressRow1, AddressRow2, AddressRow3, AddressRow4, PostCode, Telephone, mobileNumber, Email, assignedGarage)
VALUES (:surname, :forename, :addressrow1, :addressrow2, :addressrow3, :addressrow4, :postcode, :telephone, :mobilenumber, :email, :assignedgarage)");
$insertUser->bindParam(':surname', $_POST['surname']);
$insertUser->bindParam(':forename', $_POST['forename']);
$insertUser->bindParam(':addressrow1', $_POST['addressrow1']);
$insertUser->bindParam(':addressrow2', $_POST['addressrow2']);
$insertUser->bindParam(':addressrow3', $_POST['addressrow3']);
$insertUser->bindParam(':addressrow4', $_POST['addressrow4']);
$insertUser->bindParam(':postcode', $_POST['postcode']);
$insertUser->bindParam(':telephone', $_POST['telephone']);
$insertUser->bindParam(':mobilenumber', $_POST['mobilenumber']);
$insertUser->bindParam(':email', $_POST['email']);
$insertUser->bindParam(':assignedgarage', $_SESSION['garageId']);
if(!$insertUser->execute()) {
$err[] = $database->errorCode();
}
elseif ($insertUser->rowCount() == 1) {
$id = $database->lastInsertId();
echo "<script type=\"text/javascript\">
<!--
window.location = \"updateUser.php?id=$id\"
//-->
</script>";
}
if(count($err)) {
echo "<p style=\"color:red;\">The following errors were detected:</p><br/>";
foreach ($err as $key => $error) {
echo "<p style=\"color:red;\">$error</p><br/>";
}
}
I first started without defining all the columns I wanted to insert into but that didn't work so I predefined them.
My table in its early, rudimentary stages. I have my reasons for choosing varchars for mobile/telephone numbers.
Summarising, you have this:
$insertUser = $database->prepare(...);
if(!$insertUser->execute()) {
$err[] = $database->errorCode();
^^^^^^^^^
}
So you're calling PDO::errorCode() rather than PDOStatement::errorCode(). As the manual explains:
PDO::errorCode() only retrieves error codes for operations performed
directly on the database handle. If you create a PDOStatement object
through PDO::prepare() or PDO::query() and invoke an error on the
statement handle, PDO::errorCode() will not reflect that error. You
must call PDOStatement::errorCode() to return the error code for an
operation performed on a particular statement handle.
Depending on your needs and current code, you might also be interested in PDOStatement::errorInfo(), which provides error details in friendly format. And, of course, you can also instruct PDO to throw exceptions and get rid of manual error checking.
Try this instead and tell me what you find:
try{
$database->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION)
$insertUser = $database->perepare("INSERT INTO customer (Surname, Forename, AddressRow1, AddressRow2, AddressRow3, AddressRow4, PostCode, Telephone, mobileNumber, Email, assignedGarage) VALUES (:surname, :forename, :addressrow1, :addressrow2, :addressrow3, :addressrow4, :postcode, :telephone, :mobilenumber, :email, :assignedgarage)");
$insertUser->execute(array(':surname'=>$_POST['surname'], ':forename'=>$_POST['forename'], ':addressrow1'=>$_POST['addressrow1'], ':addressrow2'=>$_POST['addressrow2'], ':addressrow3'=>$_POST['addressrow3'], ':addressrow4'=>$_POST['addressrow4'], ':postcode'=>$_POST['postcode'], ':telephone'=>$_POST['telephone'], ':mobilenumber'=>$_POST['mobilenumber'], ':email'=>$_POST['email'], ':assignedgarage'=>$_SESSION['garageId']));
if ($insertUser->rowCount() == 1) {
$id = $database->lastInsertId();
echo "<script type=\"text/javascript\">
<!--
window.location = \"updateUser.php?id=$id\"
//-->
</script>";} else{
//sum'n sum'n
}catch(PDOException $e){
echo 'Error occured'.$e-getMessage();
}
This is because the $database->errorCode(); will not work for operations not directly performed on DB handle as in your case (you used PDO->prepare()). In your case this error code is reffering to last successful query not the one you are trying to execute, hence the 0000 error code.
You most likely have an error in your params array (values that are passed from $_POST). Also when using bindParams method you should specify the type of variable that is expected by database.
Form1.php
<?php
if(isset(".$_POST[fname].", ".$_POST[lname].", ".$_POST[mail]."))
{$query = "INSERT INTO table1 (fname, lname, mail) VALUES ('".$_POST[fname]."', '".$_POST[lname]."', '".$_POST[mail]."')";
$result = mysql_query($query)
or die ("Query Failed: " . mysql_error());}
else{
echo "No Values To Insert";
}
?>
I'm trying to check if the value was set, and if it wasn't-throw an error without inserting into DB.
Help?
Try
if ( isset ($_POST['fname']{0}) and isset( $_POST['lname']{0}) and isset( $_POST['mail']{0}) ){
// Insert into db
}
else{
echo "Please fill all the feilds";
}
What happens here is even if the user didnt enter any value into the fname feild, still the $_POST['fname'] will be set. So the isset ($_POST['fname']) will always return true if the form was submitted.
But when you check for isset ($_POST['fname']{0}) you are making sure that atleast one charater is entered and the feild is not empty. you can also use an is_empty but this is much better way.
Also The catch in using this is "{}" are going to be removed in php version 6. so if you are planning to upgrade your servers in the future then this might cause a small problem. But using "[]" instead of "{}" will solve that problem in php version 6.
Sorry, i read the heading of the question and mis-understood. What you have for code should work for catching failed inserts (though I recommend breaking off a test against the mysql_error instead of an or die(...)`. But, you can do an insert based on if the value already exists in the database by using this page as a reference