insert statement post page to itself issue - php

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

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.

Connecting form to SQL Database

I am able to connect to mysql database however I can not display data from my form to my database. I am not sure why this is happening but I have been able to retrieve data from my database I just can not enter information into it. For now I am just trying to enter First_Name. I also get no errors when entering in data to the form. Any help would be greatly appreciated!!
<p>
<form name="input1" action="http://seanfagan.webuda.com/Final/club.php" method="post">
First_Name:<input type="text" name="First_Name"><br>
Last_Name: <input type="text" name="Last_Name"><br>
Club_Name: <input type="text" name="Club_Name"><br>
Email: <input type="text" name="Email"><br>
Club_Type: <input type="text" name="Club_Type"><br>
Members: <input type="text" name="Members"><br>
<input type="submit" value="Send"><br>
</form>
<?php
$mysql_host = "mysql14.000webhost.com";
$mysql_database = "a9576602_Final";
$mysql_user = "a9576602_Final";
$mysql_password = "*****![enter image description here][1]";
$mysql_error = "Could not connect to database!";
$conn = mysql_connect($mysql_host, $mysql_user, $mysql_password) or die ("$mysql_error");
$select_db= mysql_select_db('a9576602_Final') or die ("Couldn't select database!");
$value = $_Post['input1'];
$sql = "INSERT INTO Club (First_Name) VALUES ('First_Name')";
if (!mysql_query($sql)) {
die('Errorss: ' . mysql_error());
}
mysql_close();
?>
</p>
Assuming your connection with the database is okay. You can put a <name> attribute for your submit button to serve as a reference for sending your form via $_POST method:
<input type = "submit" name = "input1" value = "Submit">
Then using this, you can trigger your insert statement:
<?php
if(isset($_POST['input1']))
{
// make sure you also declare the variables in your form such as the first name, etc.
$firstName = $_POST['First_Name'];
mysql_query("INSERT INTO Club (First_Name) VALUES ('$firstName')");
}
?>
Hope this helps you :D

Code doesn't write values in db

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.

How can i retrieve data from a textarea using PHP?

Given the following HTML form:
<form id="form1" name="form1" method="post" action="comments.php">
<textarea name="text" id="textarea" cols="45" rows="5"></textarea><br/>
<input type="submit" name="button" id="button" value="Update" />
</form>
...and the following PHP code (comments.php):
<?php
require("includes/config.php");
$fromtextarea = $_POST['text'];
$con = mysql_connect($dbserver, $dbusername, $dbpassword);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname , $con);
$sql = "INSERT INTO textarea (comment) VALUES ('$fromtextarea')";
if (mysql_query($sql)) {
header("Location: home.php");
}
else
echo "no no no";
mysql_close($con);
?>
How can I get the data and display all user comments on a page?
Take a look at SELECT sql statement. Your query should look like something like this:
SELECT comment FROM textarea;
Then see how to manipulate the result with mysql_fetch_* functions in PHP (http://www.php.net/manual/fr/function.mysql-fetch-assoc.php).
By the way, mysql_* functions are deprecated (and will be deleted soon). I advise you using mysqli_* functions (http://www.php.net/manual/fr/book.mysqli.php) or (better) PDO (http://php.net/manual/fr/book.pdo.php).
Do like this
$sql = "INSERT INTO textarea (comment) VALUES ('". $_POST["text"] . "')";
Make sure you sanitize it before using it in your query.

MySql is not updating

please help..i give up..
trying to update MySql table..
the file is settings.php (self-submitting)
form code is:
<form method="POST" action="settings.php">
First Name <input type="text" name="fname" id="set_fname" />
Last name <input type="text" name="lname" id="set_lname" />
Email: <input type="text" name="email" id="set_email" />
mobile <input type="text" name="mobile" id="set_mobile" />
Bio: <textarea name="bio" id="set_bio" cols="" rows="5" maxlength="1000" ></textarea>
<input type="submit" id="personal_submit" value="Update" />
</form>
php part
$id=$_SESSION['id'];
$fname_update =$_POST['fname'];
$lnam_update = $_POST['lname'];
$email_update = $_POST['email'];
$mobile_update =$_POST['mobile'];
$bio_update =$_POST['bio'];
$db_host="localhost";
$db_uname="admin";
$db_pass="mypass";
$db_db="main_db";
$db_table="mebers_general";
mysql_connect("$db_host","$db_uname","$db_pass") or die (mysql_error());
mysql_select_db("$db_db") or die("no database by that name");
if($_POST['fname']){
$sql_personal_update=mysql_query("UPDATE members_general SET first_name='$fname_update' WHERE id='$id' ") or die (mysql_error()) ;
if($sql_personal_update){
echo "should be ok but no record is updated....Heeelppp";
}else{
echo "Smth is Wrong";
}
}
I get no errors..
as a result i get the echo string "should be ok but no record is updated....Heeelppp";
so it detects no problem in updating
I've tried the same query in phpMyadmin - works just fine.
I checked the variables - they are not empty..
everything seems to be as it should.
Please help..stacked for 2 days already here//
$sql_personal_update=mysql_query("UPDATE members_general SET firs_name='".$fname_update."' WHERE id='".$id."' ") or die (mysql_error()) ;
You are not actually RUNNING your query:
$sql_personal_update=("UPDATE members_general SET firs_name='$fname_update' WHERE id='$id' ") or die (mysql_error()) ;
^^^^^--- where's mysql_query()?
It should be
$sql_personal_update = mysql_query(blah blah blah) or die(mysql_error());
I guess it's because you're not actually calling the mysql_query function!
For starters, try
$sql_personal_update=mysql_query("UPDATE members_general SET firs_name='$fname_update' WHERE id='$id' ") or die (mysql_error()) ;
Also, is firs_name a typo, or did you really call your database column that?
EDIT: As JoachimIsaksson suggested, mysql_connect etc are deprecated. Use mysqli instead, like below:
$mysqli = new mysqli($db_host,$db_uname,$db_pass, $db_db) or die (mysql_error());
if($_POST['fname']){
$sql_personal_update=$mysqli->query("UPDATE members_general SET first_name='$fname_update' WHERE id='$id' ") or die (mysql_error()) ;
if($sql_personal_update) {
echo "should be ok but no record is updated....Heeelppp";
} else {
echo "Smth is Wrong";
}
}
Thanks for everything, guys, i just recoded all page from blank and it worked..have no idea what was the reason..maybe the 20th hour in a row of coding..thanx..

Categories