HTML form will not submit - php

This is my form
<html>
<head><title>Hawkins Car Records</title></head>
<body><h1>Add New Car</h1></body>
<form action="carNewBack.php" method="POST">
Car Name: <input type="text" name="carName"/>
<br>
Make: <input type="text" name="make"/>
<br>
Model: <input type="text" name="model"/>
<br>
Year: <input type="text" name="year"/>
<br>
Last 5 digits of VIN: <input type="text" name="lastVIN"/>
<br>
Plate: <input type="text" name="plate"/>
<br><br>
<input type="submit" value="Submit"/>
</form>
</html>
When I hit the submit button, nothing happens. No white screen, no 404, nothing. It doesn not execute carNewBack.php. Can someone share any ideas?
Here is the action file. Im trying to build a data base of service records of my family's cars and this is the form that takes input and creates a new car record.
<?php
$carconnect = mysqli_connect("localhost", "carUser", "caps271:snows", "cars");
if (mysqli_connect_errno()) {
printf("connect failed: %s\n", mysqli_connect_error());
exit();
} else {
$carName = mysqli_real_escape_string($_POST['carName']);
$make = mysqli_real_escape_string($_POST['make']);
$model = mysqli_real_escape_string($_POST['model']);
$year = mysqli_real_escape_string($_POST['year']);
$lastVIN = mysqli_real_escape_string($_POST['lastVIN']);
$plate = mysqli_real_escaped_string($_POST['plate']);
$sql = "INSERT INTO cars (carName, make, model, year, lastVIN, plate) VALUES ('". $carName."', '".$make."', '".$model."', '".$year."', '".$lastVIN."', '". $plate."')";
$res = mysqli_query($carconnect, $sql);
if ($res === TRUE) {
echo "Car added";
} else {
printf ("Could not insert car: %s\n", mysqli_error($carconnect));
}
mysqli_close($carconnect);
}
?>
Edit: Code fixes.

your <body> tag is closed too early (on line 3), you should close it right before </html> so on line 18

Dear brother its simple..
check out your header there must be something like:
error_reporting(0); or something like that in your php.ini file to Suppress the errors.
2.There is no valid default function as mysqli_real_escaped_string(); unless you have it user defined.
It is mysqli_real_escape_string();
kindly have a look at mysqli_real_escape_string()
hope it was helpful :)

if carNewBack.php is not printing anything back to the screen or redirecting the page. What are using to host the website? If you do not have a web service that does not have php support then this could be an issue.

The form you submitted looks correct (http://www.w3schools.com/php/php_forms.asp), I imagine the real issue could lie in the php handler. If you do not get an error, that means that it does find the php handler.
I also tested your code and it looks fine, so another option could be the browser you are using or even the zoom (I use Google Chrome).

Related

How to generate Self Created pages dynamically?

I am working on classified website in which user will post his ads to sell something. It is basically my first web project. I have problem in making self creating pages in which when user post his ad it will generate an HTML page automatically and link and little glimpse of his ad show on a proper well designed another ad page.
Here I have described my problem properly:
When user presses submit ad button an html page will be created automatically and user will be directed to that page (how to create that page)?
How to place link of ad page on the top of other previous ads those are too on self-created page dynamically?
Here is random code of inserting and displaying database on the page:
<!DOCTYPE html>
<html>
<body>
<form action="zain.php" method="post">
Topic: <input type="text" name="topic"><br />
<br />
Name: <input type="text" name="name"><br /><br />
Attendance: <input type="text" name="attendance"><br />
<br />
<input type="reset" name="reset">
<input type="submit" name="submit" value="Go">
</form>
<?php
$user = 'root';
$password = 'zz224466';
$db = 'Zain';
// Create connection
$conn = mysqli_connect('localhost', $user, $password, $db);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "";
mysqli_select_db($conn, "zain");
$insert = "INSERT INTO lectures (Topic,Name,Attendence) VALUES('$_POST[topic]','$_POST[name]','$_POST[attendance]')";
mysqli_query($conn,$insert);
///////////Write records on the Screen//////////////
$sql = "SELECT * FROM lectures";
$myData = mysqli_query($conn,$sql);
while($record=mysqli_fetch_array($myData)){
echo $record['Topic']. " "
." ". $record['Name']." ".$record['Attendence'];
echo "<br>";
}
mysqli_close($conn);
?>
</body>
</html>
Can you please show me some hints to solve my problem?
After adding lecture you can get id of record in database by function
$id = mysqli_insert_id($conn);
You can prepare new page with id on it for example:
page.com/lecture.php?id=3
Where id is your lecture id to generate. Under this site you should prepare php code to show exactly this lecture.
To redirect to new lecture page you can check this post: How to make a redirect in PHP?
Links to other ads can be easly added by changing id in url.
PS. You shouldn't put $_POST parameters directly to database, there is a possibility of SQL injection, use http://php.net/manual/en/mysqli.real-escape-string.php
As gonzalo commented, you don't need to create an html page. Rather save the details into DB and create a dynamic (.php) file; and let this file do all the work. ie. Pass on the id of the ad to that file; fetch the details from the db and present it to the user using html markup. That being said, I strongly recommend to use a framework.
If at all you want to create fresh page each time (though i too wouldn't recommend that), you can store your data into variables and create a page with fopen() and fwrite() and then add header('location:file.ext') to redirect it to that url

PHP Not Inserting Content in mySQL Database: Text, Images, Anything

So here is my dilemna that I've been reviewing and trying to break through for the last few days. I've created a basic login/register PHP system, which works fine. I've implemented a blog system that displays posts. I've written an add post function which does not post to the database, and it doesn't throw back an error function either.
I don't really understand because my register system works and adds new users, but the 'add blog post' does nothing. I can add from the database and it displays fine, but nothing here.
<?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();
if (isset($_SESSION['id'])) {
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
} else {
header('Location: login.php');
die();
}
if ($_POST['submit']) {
$title = strip_tags($_POST['title']);
$subtitle = strip_tags($_POST['subtitle']);
$content = strip_tags($_POST['content']);
mysqli_query($dbCon, $userREQ3);
$userREQ3 = " INSERT INTO `logindb`.`blog`
(`title`, `subtitle`, `content`) VALUES ('$title','$subtitle','$content')";
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Welcome, <?php echo $username; ?>, You are logged in. Your user id is <?php echo $userId; ?>.
Index
<form action="logout.php">
<input type="submit" value="Log me out!">
</form>
<form method="post" action="admin.php">
Title: <input type="text" name="title"/><br>
Subtitle: <input type="text" name="subtitle"/><br>
<br>
<br>
Content: <textarea name="content"></textarea>
<input type="submit" value="Write Post"/>
</form>
</body>
</html>
Your code is failing for two reasons.
Your conditional statement is looking for a named element called "submit"
You're trying to execute before the statement. Place your query (mysqli_query())"below" the values and do mysqli_query($dbCon, $userREQ3) or die(mysqli_error($dbCon));
Sidenote: Change if ($_POST['submit']) { to if (isset($_POST['submit'])) { it's better.
and <input type="submit" value="Write Post"/>
to <input type="submit" name="submit" value="Write Post"/>
SQL injection:
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
Also, you have variables in the body of your code, which may throw undefined variable x on initial page load.
Use a ternary operator for this
http://php.net/manual/en/language.operators.comparison.php
Use this for all your inputs/variables
As stated (in comments below): Make sure that you have connected to your database and using a mysqli method and not another API.
https://secure.php.net/mysqlinfo.api.choosing
Different MySQL APIs do not intermix with each other. Use the same MySQL API from connection to query.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Successful query or not:
To see if the query was indeed successful, or failed, check for errors and use affected_rows.
References:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/mysqli.affected-rows.php
PHP Not Inserting Content in mySQL Database: Text, Images, Anything
If you were trying to use images, then a valid enctype is required to be included in the form tags.
Depending on how/what you wanted to insert for the images, than that could be a factor.
If you're wanting to insert the image as a path is one thing, but using it "as an image", say a BLOB then that has limitations in size; use LONGBLOB and you must escape that data before going in the database.
Consult:
https://dev.mysql.com/doc/refman/5.0/en/blob.html
http://php.net/manual/en/features.file-upload.post-method.php
Try to generate the query first, then execute it...
$userREQ3 = " INSERT INTO `logindb`.`blog`
(`title`, `subtitle`, `content`) VALUES ('$title', '$subtitle','$content')";
mysqli_query($dbCon, $userREQ3);

How to restrict update or insert more than once by navigating back to referring page in php?

I am developing a web application where I want to restrict update or insert more than once by navigating back to referring page. Let me present you three model files in the order of flow so that I can raise the zone where I am stuck.
register.html
<html>
...
<form id="form1" name="form1" method="post" action="process.php">
<label for="textfield">Name</label>
<input type="text" name="name" id="name" />
<input type="submit" name="Submit" value="Submit" />
</form>
...
</html>
process.php
<?php
echo "Welcome ".$_GET['para'];
?>
success.php
<?php
if(isset($_POST['Submit']))
{
$name = $_POST['name'];
// some database update here ...
echo "<a href='success.php?para=$name'>Done. Click to go next</a>";
unset($_POST['Submit']);
}else{
echo "Error in submission";
}
?>
The above three files are very simple. Here the update part has nothing to do when the user hits the back button after landing on page success.php because of unset($_POST['Submit']);. But when the user goes back further by hitting the back button again it reaches register.html and can again come up with the $_POST['Submit'] set and may do the update part which is sometimes vulnerable. I know there is Post/Redirect/Get to solve this issue, but I want some other alternatives so that the part gatekeepering the update part may be made so efficient that it would not allow the same anymore by clicking the back button.
If you are getting duplicate records inserted.
You may try INSERT IGNORE
ADD UNIQUE INDEX to your table to prevent this happening
you may choose any one of INSERT IGNORE and REPLACE according to the duplicate-handling behavior
Refer https://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html
Lastly you may like simple php with mysqli_num_rows()
$sql = "SELECT id FROM table-name WHERE column-name1 = ? AND column-name2 = ? ;
$mq = mysqli_query($sql);
if (mysqli_num_rows($mq) < 1) {
$sql = "UPDATE table-name SET (colum-names) VALUES (...)";
mysqli_query($sql);
else {
echo "Record already updated";
}
}

Empty rows created by refreshing page

I've searched on the Internet to get my answer, but I couldn't find a helpful one. I've got a page called 'post.php' with a form where I can add an image and submit it to the database.
The big problem is when I go to mysite.com/post.php a new empty row is created automatically in the database, which I clearly don't want. I want only to update the database after clicking on the submit button my code:
the part of INSERT:
<?php
// POST.PHP POSTING NEW CONTENT
include 'config.php';
// values from form
$id=$_POST['id'];
$title=$_POST['title'];
$pic=$_POST['pic'];
$youtube=$_POST['youtube'];
$cat=$_POST['cat'];
// insert data to mysql
$sql = "INSERT INTO post(id, title, pic, youtube, cat)VALUES('$id', '$title', '$pic', '$youtube', '$cat')";
$result=mysql_query($sql);
// succes added
if(!$result){
echo "Something went wrong!";
}
else {
echo "Yeah, buddy! Your content is added.";
}
// end of post script ^^
?>
// end of insert
//POST IMAGE PAGE
if(isset($_GET['pic'])) {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
title: <input name="title" type="text" id="title"><br />
Add url of image;<br />
<input type="text" name="pic" id="pic"/><br />
<?php
echo '
Category game:
<select name="cat"> ';
$query2 = mysql_query("SELECT * FROM `category`");
while($row=mysql_fetch_array($query2)){
echo '
<option value="'.$row["nameID"].'">'.$row["name"].'</option> ';
}
?>
</select>
<input type="submit" onclick="this.disabled = true" name="submit" value="submit">
</form>
<?php
// end script of posting picture
}
?>
You need to add some conditional code around the part that inserts into the database, checking for if any values has been received (if($myvar){ // do stuff }).
Add the rest of your code, specifically the part that adds stuff to the database as that is what's causing you problems, not the code you posted.
You need to wrap the whole block of database insertion code in an if statement. That way, it will not execute until the form has been submitted and $_POST['submit'] has a value:
include 'config.php';
if (isset($_POST['submit'])){
// values from form
$id=$_POST['id'];
// etc... code stays the same down to:
echo "Yeah, buddy! Your content is added.";
}
}//end if (don't forget to add this last bracket)
Also, you should switch to mysqli or PDO, and use parameterized queries. Otherwise, your site is open to a variety of gnarly attacks via SQL injection. It's not that hard to switch, and very, very important.
Check if the post have been set on the file that handles the database input.
if(isset($_POST['pic'])){
//do something
}
else{ // handle the exeption}
Also, you should not use mysql_* functions anymore. they are unsafe and deprecated as-of php 5.5

what is the equivalent of ispostback(.NET) in PHP?

I just start coding in PHP,
i wrote my first php + mysql program for inserting data through web form. it works fine, but whenever i refresh the page, it automatically saves null record to my database.
i know the solution in .NET is ispostback, but not in php?
can somebody give me some idea in PHP.
Code is here:
<body>
<form action="mySQLTest.php" method="post">
First Name :<input type="text" name ="txtFirstName"/> <br/>
Last Name: <input type="text" name ="txtLastName"/> <br/>
Age : <input type="text" name= "txtAge" /> <br/>
<input type="submit"/>
</form>
<?php
$con = mysql_connect("localhost","root","");
if(!$con)
{
die('Could not Connect:' .mysql_error());
}
mysql_select_db("test", $con);
if($_REQUEST[])
{
$sql1 = "Insert into info(FirstName, LastName, Age) Values('$_POST[txtFirstName]','$_POST[txtLastName]','$_POST[txtAge]')";
}
if(!mysql_query($sql1, $con))
{
die('Error: '.mysql_error());
}
else
{
echo "1 Record Added";
}
mysql_close($con)
?>
</body>
Have you tried if ($_SERVER['REQUEST_METHOD']=='POST')
updated answer:
if ($_SERVER['REQUEST_METHOD']=='POST') {
[insert...]
header('Location: added_record.php');
}
When you use the POST-method, it's better (imho) to use $_POST rather than $_REQUEST. To check whether you have data, you could use isset($_POST['txtFirstName']);. If you need all data, it's best to do this for all input fields, resulting in
if(isset($_POST['txtFirstName']) && isset($_POST['txtLastName']) && isset($_POST['txtAge'])) {
// do stuff
}
If you want to know if there was any field submitted using post, you could use if(!empty($_POST)) {.
On a side note: I know you are just starting PHP, it could be quite dangerous to use user-generated code in queries. When you are building stuff online, for everyone to reach, please read a bit about SQL injection. This will also prevent your code from breaking when someone enters an apostrophe (').

Categories