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.
Related
I want it so that when the user types into the textarea/input and clicks save changes, the information they input has been added and saved into the database. Below is my code:
$name = $_SESSION['u_name'];
$uid = $_SESSION['u_uid'];
$id = $_SESSION['u_id'];
$con = mysqli_connect("localhost", "root", "pass123", "db_name");
if ($con->connect_error) {
die("Connection failed: " . $conn->connect_error);
echo "<script type='text/javascript'>alert('connection failed. try again');</script>";
}
$remind1 = $_POST['remind1'];
$remind2 = $_POST['remind2'];
$remind3 = $_POST['remind3'];
$remind4 = $_POST['remind4'];
$remind5 = $_POST['remind5'];
if (isset($_POST['updBtn'])){
$sql = "UPDATE reminders SET remindone='$remind1' WHERE username='$uid'";
if ($con->query($sql) === TRUE) {
echo "<script type='text/javascript'>alert('Updated successfully');</script>";
}else{
echo "<script type='text/javascript'>alert('error while updating. try again');</script>";
}
}
Below is the corresponding HTML:
<form action="body.php" method="post">
<input type="submit" class="sideBtn" value="Save Changes" name="updBtn"><br>
<input type="text" class="event" name="remind1"><br>
<input type="text" class="event" name="remind2"><br>
<input type="text" class="event" name="remind3"><br>
<textarea class="event" name="remind4"></textarea><br>
<textarea class="event" name="remind5"></textarea><br>
</form>
Ideally what would happen, is that whatever the user types into the textarea/input is updated in the database, then they can access and later tweak the text if they need to.
I have been able to pinpoint that my problem is somewhere along the $_POST variables in my PHP as, if I were to substitute the aforementioned variable with a string as such:
$sql = "UPDATE reminders SET remindone='hello' WHERE username='$uid'";
...it works perfectly. But with when using the POST variable, it does not work.
How can I fix this mistake of mine and make it so that the user is able to post text into the database? Is the $_POST variable required here or is there another method to achieve this?
I have a form in HTML, but it's not setup like normal I guess. I'll post the code form the HTML (PHP) file and the php to send it to the db.
<form action="upload.php" method="POST">
<!-- Name input-->
<div class="form-group">
<label class="control-label" for="name">Name</label>
<div class="">
<input id="name" name="name" placeholder="First and Last Name" class="form-control input-md" type="text" required>
</div>
</div>
<div class="form-group">
<label class=" control-label" for="supportingDoc">Upload Supporting Documentation</label>
<div class="">
<input id="supportingDoc" name="supportingDoc" class="input-file" type="file" style="margin-top: .5em; margin-left: 4em;">
</div>
</div>
<hr>
<!-- Submit -->
<div class="form-group">
<label class="control-label" for="submit"></label>
<div class="">
<button value="Submit" type="submit" id="submit" name="submit" class="btn btn-danger" style="border-radius: 25px;">Submit</button>
</div>
</div>
</form>
Here is my SQL/PHP
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$con = mysqli_connect("localhost","xxx","xxx","xxx");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_REQUEST['name'])){
// set variables
$name = mysql_real_escape_string($_POST['name']);
$supportingDoc = mysql_real_escape_string($_POST['supportingDoc']);
$sql = "INSERT INTO `tablew` (name, supportingDoc) VALUES ('$name', '$supportingDoc')";
$result = mysqli_query($con,$sql);
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
printf("New record created successfully");
} else {
echo "Error: " . $sql . "<br>" . $con->error;
printf("Error: " . $sql . "<br>" . $con->error);
}
$con->close();
}
?>
I've tried all sorts of variations and nothing is showing in phpmyadmin. I've even replicated from a previous site I created and it still didn't work lol.
I see that there are variables for the login info and still put it in the mysqli, but I've been at this one thing for about 8 hours now and am out of juice, so hopefully someone sees what I messed up on.
Thanks in advance for any help everyone.
===========================================================================
UPDATE:
I made all the changes mentioned above and now get this:
Warning: mysqli_connect(): (HY000/1049): Unknown database
I can see the database in phpmyadmin and Sequel Pro. I've also made sure to set the password and login to 'root'. My code is as follows for login:
$con = mysqli_connect("localhost","root","root","epboarding");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
and this is my POST:
if (isset($_REQUEST['submit'])){
// set variables
$name = mysqli_real_escape_string($con, $_POST['name']);
$sql = "INSERT INTO `wos` (name) VALUES ('$name')";
$result = mysqli_query($con,$sql);
Following issues can be there:
Uploading error. Use enctype="multipart/form-data" in form tag.
Correct Mysql_connect details i.e. Username, Password, Dbname.
mysql_real_escape_string is depricated. Use mysqli.
Recheck your column names i.e. name, supportingDoc.
Your html code wrong. Whenever you want to use input type file, you need to put <form> tag to <form enctype="multipart/form-data">. If you re not declaring the enctype, then the PHP cannot read the file.
you have to put
<form enctype="multipart/form-data">
when uploading file . correct your html.
Try This
The issue is after clicked on submit button it's not hitting the (isset($_REQUEST['name']))
Change it
if (isset($_REQUEST['submit'])){ //code here}
because you button name is submit.
Use SQL injection like
$con->real_escape_string($_POST['name']);
for the unknown database error. I simply went to operations in phpmyadmin and changed the name of the database and it worked. give it a try if you haven't fixed the problem yet.
in addition to #tbi
answer
Check php.ini for max post size it cause the POST request to fail if the size exceeds the size set in php.ini
post_max_size=20M
upload_max_filesize=20M
check your SQL connection and your permissions on the DB
use enctype="multipart/form-data" in your form only when you need to upload files (for security reasons)
finally, don't forget to bind your post params to prevent SQL-Injection
Params Binding
If you are using a default account on a local installation, then your connection code will probably look like this:
<?php $con = mysqli_connect('localhost','root','');
mysqli_select_db('epboarding', $con); ?>
use enctype="multipart/form-data" in form tag when you use file type.
<form name="" method="POST" action="" enctype="multipart/form-data">
3.change the following line
if (isset($_REQUEST['name'])){
to
if (isset($_REQUEST['submit'])){
correct the syntax when post data like mysql to mysqli.
From the PhpMyAdmin screenshot, it looks like the database is running on port 8889, meaning you would need:
$con = mysqli_connect("localhost","xxx","xxx","xxx", 8889);
In addition to what the others have said, I thought I'd provide a tidied script and some (hopefully) useful resource for you other issues.
http://php.net/manual/en/mysqli.construct.php
What's wrong with using $_REQUEST[]?
https://www.w3schools.com/sql/sql_injection.asp
As for your unknown database error this is either your database doesn't exist, is incorrectly named in your PHP script or is unavailable through localhost.
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli ( $servername, $username, $password, $dbname );
// Check connection
if ( $conn->connect_error ) {
echo "Failed to connect to MySQL: " . $conn->connect_error;
}
// Check if values are set with post rather than request, as this is deprecated and can output unexpected results
if ( isset( $_POST['name'] ) ) {
// Set variables
$name = $_POST['name'];
$supportingDoc = $_POST['supportingDoc'];
// Prepare a statement and bind parameters to prevent sql injection
$stmt = $conn->prepare( "INSERT INTO `tablew` (name, supportingDoc) VALUES (?, ?)" );
$stmt->bind_param( 'sb', $name, $supportingDoc );
if ( $stmt->execute() ) {
echo "New record created successfully";
printf( "New record created successfully" );
} else {
echo "Error: " . $stmt->error;
printf( "Error: " . $stmt->error );
}
$stmt->close();
$conn->close();
}
The code below should write code into the database.
I have divided into two parts HTML AND PHP code are separate. HTML form code is shown below:
<form name="form1" action="insert.php" method="post">
<h3>Ime </h3> <input type="text" name="field1" > <br/> <br/>
<h3>Prezime </h3> <input type="text" name="field2" > <br/> <br/>
<h3>Firma </h3> <input type="text" name="field3" > <br/> <br/>
<h3>Adresa </h3><input type="text" name="field4" > <br/> <br/>
<h3>Telefon </h3> <input type="text" name="field5" > <br/> <br/>
<h3>Fax </h3><input type="text" name="field6" > <br/> <br/>
<h3>Mobitel </h3> <input type="text" name="field7" > <br/> <br/>
<h3>Email </h3> <input type="text" name="field8" > <br/> <br/>
<h3>Web stranica </h3> <input type="text" name="field9" > <br/>
</form>
PhP code is shown below.
$host="localhost"; // Host name
$username="root"; // username
$password="le30mu09"; // password
$database="imenik"; // Database name
$tbl_name="clanovi"; // Table name
// Replace database connect functions depending on database you are using.
$field1=$_POST['field1'];
$field2=$_POST['field2'];
$field3=$_POST['field3'];
$field4=$_POST['field4'];
$field5=$_POST['field5'];
$field6=$_POST['field6'];
$field7=$_POST['field7'];
$field8=$_POST['field8'];
$field9=$_POST['field9'];
$link=mysql_connect("$host", "$username", "$password");
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db("$database");
if (!$db_selected) {
die ('db is not selected : ' . mysql_error());
}
$query = "INSERT INTO `clanovi`(`Ime`, `Prezime`, `Firma`, `Adresa`, `Telefon`, `Fax`, `Mobitel`, `Email`, `Web_stranica`) VALUES ( "$field1", "$field2", "$field3", "$field4", "$field5", "$field6", "$field7", "$field8", "$field9")";
mysql_query($query);
mysql_close();
You need to tell us what the actual error is. And bone up on PDO and the dangers of sending unsanitised POST variables to the DB as a matter of priority.
Modify your Insert query. It should be like this:
INSERT INTO clanovi
(column1,column2,column3,...)
VALUES
( $field1, $field2, $field3,.....)
You appear to be using a lot of quotation marks in places that you shouldn't be using them in. It is funny how you can code something for 5 hours and then try to debug it for 2 hours because of a simple quotation mark! It's funny and very depressing at the same time :(
Ok, let's fix the code a little bit!
Database
$link=mysql_connect($host, $username, $password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db($database);
if (!$db_selected) {
die ('db is not selected : ' . mysql_error());
}
Notice how I stripped all of the quotation marks out of the code? That will help with database connection and selection.
Now let's move onto the actual inserting of the information into the database!
$query = "INSERT INTO clanovi ('Ime', 'Prezime', 'Firma', 'Adresa', 'Telefon', 'Fax', 'Mobitel, 'Email', 'Web_stranica') VALUES ( $field1, $field2, $field3, $field4, $field5, $field6, $field7, $field8, $field9)";
Again, I stripped all of the quotation marks. Plus I removed backticks and replaced with a ' and also took the '' off of your table name - You should nly use quotation marks when not using a variable.
//Correct
VALUES ($field1, "textnotvariable", $field2...
//Incorrect
VALUES ("$field1", "textnotvariable", "field2"...
The same goes with echo statements. Here's an example...
$myname = "MrJustin";
//Correct
echo $myname;
//or
echo "My name is ". $myname .", it's nice to meet you!";
//Incorrect
echo "My name is $myname, it's nice to meet you";
You'll notice how I used ". $myname ." - that tells the echo to break away from using text, and to pass a variable! :) That to me is the best way to explain how quotations will break a code.
Oh, and you should ALWAYS sanitize your inputs/outputs when using foreign code. I would do some Google searching on that one, and then chat us back up if you run into problems with that!
Hopefully this helps, and happy coding!!
you are not selecting database. you are using double quotes in not its place.
replace this
$db_selected = mysql_select_db("$database");
by
$db_selected = mysql_select_db($database);
and also replace this
$link=mysql_connect("$host", "$username", "$password");
by
$link=mysql_connect($host, $username, $password);
i recomand you to use PDO or mysqli instead.
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
I am trying to submit the page to itself but some reason the following code is not working. Also How can I get the table1 primary key ID back after inserting the data successfully? I have a child table which needs this ID. Thanks for any suggestions.
<?php
include('db_login.php');
$connection = mysql_connect( $db_host, $db_username, $db_password );
if (!$connection){
die ("Could not connect to the database: <br />". mysql_error());
}
// Select the database
$db_select=mysql_select_db($db_database);
if (!$db_select){
die ("Could not select the database: <br />". mysql_error());
if ($_POST['Submit'])
{
$first = $_POST["first"];
$first = mysql_real_escape_string(get_magic_quotes_gpc() ? stripslashes($first): $first);
$last = $_POST["last"];
$last = mysql_real_escape_string(get_magic_quotes_gpc() ? stripslashes($last): $last);
$insertsql = "INSERT INTO table1(FirstName,LastName) VALUES ('".$first."', '" .$last. "')";
$result1 = mysql_query($insertsql) or die(mysql_error());
}
?>
<form name="hotlineForm" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>"
method="post">
<input id="first" type="text">
<input id="last" type="text">
<input type="submit" value="Submit"></form></body>
What part isn't working on the post back? Are you not entering your if statement?
To get the ID of the last insert use the following after your $result1 = mysql_query(...):
$primary_id = mysql_insert_id()
http://php.net/manual/en/function.mysql-insert-id.php
Change your form inputs to include name attributes. Without them, your $_POST will be empty.
<input name='first' id="first" type="text">
<input name='last' id="last" type="text">
<input name='Submit' type="submit" value="Submit">
As mentioned in the comments, get_magic_quotes should not be used. You've correctly called mysql_real_escape_string() on your inputs already.
Following your insert, get the id from mysql_insert_id():
$result1 = mysql_query($insertsql) or die(mysql_error());
$new_id = myqsl_insert_id();
if ($_POST['Submit'])
I don't see a form element with this name.
try:
if (isset($_POST['first']) && isset($_POST['last']))
For getting inserted ID you can use:
mysql_insert_id();
You are missing a closing } here:
if (!$db_select){
die ("Could not select the database: <br />". mysql_error());
} <<---- Close your if statement here.
if ($_POST['Submit'])
Currently the code that does the actual work only gets called if the DB cannot be selected.
Not very useful.
This is why proper indentation is important.
If you are religious about your indentation, you will spot these kind of errors instantly.
Use a name for the input field and check if it was sents not the submit