Retrieve data from database and display in text fields. - php

Please help me. I written a code but it is not working well.
I want to retrieve data from database and display text fields.
My Code is:
<DOCTYPE html>
<html>
<head><title>Practice</title></head>
<body align="center">
<?php
$con=mysqli_connect("localhost","root","","address_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<form action="1.php" method="post">
Name <br><input type="text" name="name" value="<?php echo $_GET['n']; ?>"><br>
Address 1<br><input type="text" name="address_1" value=""><br>
Address 2<br><input type="text" name="address_2" value=""><br>
Address 3<br><input type="text" name="address_3" value=""><br><br><br>
<input type="submit" name="reset" value="Clear">
<input type="submit" name="submit" value="Submit">
<input type="submit" name="retrieve" value="Retrieve">
</form>
<?php
if (isset($_POST['submit']))
{
$name=$_POST['name'];
$address_1=$_POST['address_1'];
$address_2=$_POST['address_2'];
$address_3=$_POST['address_3'];
if(($name=='')||($address_1=="")||($address_2=="")||($address_3==""))
{
echo "<script>alert('Please fill all fields')</script>";
exit();
}
else
{
mysqli_query($con,"INSERT INTO address_tbl (name,address_1,address_2,address_3)
VALUES ('$name','$address_1','$address_2','$address_3')");
echo "<script>alert('Your record successfull inserted into database...')</script>";
exit();
}
}
if (isset($_POST['retrieve']))
{
$result = mysqli_query($con,"SELECT * FROM address_tbl");
while($row = mysqli_fetch_array($result))
{
$name=$row['name'];echo "<br>";echo "<br>";
$add1=$row['address_1'];echo "<br>";echo "<br>";
$add2=$row['address_2'];echo "<br>";echo "<br>";
$add3=$row['address_3'];echo "<br>";echo "<br>";
echo "<script type='text/javascript'>
window.open('1.php?n=$name','_self'); </script>";
}
}
?>
</body>
</html>
Please help me. give me any hint that I can solve my problem. Thanks

try this ,
mysqli_query($con,"INSERT INTO `1address_tbl` (`name`,`address_1`,`address_2`,`address_3`)
VALUES ('$name','$address_1','$address_2','$address_3')");
it should work fine now. it needs to include ( ` ) around the table names and column name to make sql work correctly. you left them out,
you replace this with yours.

First of all you should have your php in a seperate file called index.php with just php code then create a page called index.html.php in that page use a foreach loop to output data from the database its the most common and practical way of doing what your trying to do .

Related

SQL insert statement with user input to Phpmyadmin isnt working

I was trying to make a site and people could sign up/subscribe and i would store their email adresses in a database. I searched online for a solution but couldnt find anything
My code:
<html>
<?php include_once('include/html/hoofd.php') ?>
<body>
<h1 id="css"> ----- </h1>
<br><br><br>
<ul>
<form method="post" action="./emailverwerk.php" class="email" id="css2">
<b><extra space >Register and we will notify you with the the next GREAT deal!</b><br>
<br>
Full Name: <input type="text" class="css2" name="naam" placeholder="Full name"><br>
Email adress : <input type="email" class="css2" name="emailaddress" placeholder="Email Adress"><br>
Email adress : <input type="email" class="css2" name="Emailaddressrepeat" placeholder="Repeat Email "><br>
<a href="http:/----------/emailverwerk.php"><input type ="Submit" value ="Subscribe" id="css3"><br>
<?php
session_destroy();
if (isset($_SESSION["error"])) {
print ($_SESSION["error"]);
}
?>
</form>
</ul>
<ul>
<form method="post" class="actie" id="expired1">
<b>- Claim your free 1000 TRX here!!</b><br>
This is a one time offer! <br>
Click the link below and fill in your details to claim your free 1000 TRX!<br>
<input type="submit" value="Expired!!" id="css3">
</form>
</ul>
</body>
</html>
And my SQLI code :
<?php
session_start();
include_once ("include/database.php");
$name = $_POST["naam"];
$email = $_POST["Emailaddress"];
$emailherh = $_POST["Emailaddressrepeat"];
$sql = "INSERT INTO emaillist (naam , email)
VALUES ('".$_POST["naam"]."','".$_POST["emailaddress"]."')";
if ($conn->query($sql) === TRUE) {
echo "<script type= 'text/javascript'>alert('New record created successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error."');</script>";
}
$conn->close();
}
?>
Im a first year student as well so my programming experience isnt that big and perfect yet.
You must escape the strings. Else you are disallowing Irish. Think what happens with O'Brian. It will give you a mysterious "syntax error".
Your Anchor tag is not needed around the form submit, and it was not closed .

$_SERVER['PHP_SELF'] -Xampp Error

<html>
<body>
<h1>NewsLetter Registration Time! </h1>
<form action='$_SERVER["PHP_SELF"]' method='post'>
Enter the username to be added:
<input type="text" id="nt1" name="username"/>
Enter the corresponding email-id to be added:
<input type="text" id="nt1" name="email_id"/>
<input type="submit"/>
<?php
if(isset($_POST['submit']))
{
echo "<h1 style='color:red;'> Entering Data..... </h1>";
$database=mysqli_connect('localhost','root','','userdetails')
or die("didn't work");
mysqli_query($database,"INSERT INTO userdetails (username,password)VALUES ($_POST[username],$_POST[email_id])");
mysqli_close($database);
echo "<h3 style='color:red;'> Check the database..... </h3>";
}
?>
</body>
</html>
I am not able to access Database using $_SERVER['PHP_SELF'] but the code works if I use some other php script in action. Is this a problem with xampp?
Error:
You are missing php tag in your forms and type=submit in your submit button. Also, check the manual for inserting data in database using php
<html>
<body>
<h1>NewsLetter Registration Time! </h1>
<form action='<?php $_SERVER["PHP_SELF"];?>' method='post'>
Enter the username to be added:
<input type="text" id="nt1" name="username"/>
Enter the corresponding email-id to be added:
<input type="text" id="nt1" name="email_id"/>
<input type="submit" name="submit"/>
<?php
if(isset($_POST['submit']))
{
echo "<h1 style='color:red;'> Entering Data..... </h1>";
$database=mysqli_connect('localhost','root','','userdetails')
or die("didn't work");
mysqli_query($database,"INSERT INTO userdetails (username,password)VALUES ('$_POST[username]','$_POST[email_id]')");
mysqli_close($database);
echo "<h3 style='color:red;'> Check the database..... </h3>";
}
?>
</body>
</html>

MySql search script writes an unkown error

This is my second post on stackoverflow, and i hope u will help me resolve this one too.
When i run this script it says "Undefined variable: search_name".i don't know what is problem.
Hope u are going to help.
Ty :D .
<?php
$con=mysqli_connect("localhost","root","","test");
if (mysqli_connect_errno())
{
echo "Error" .mysqli_connect_error();
}
if(isset($_POST['go']))
{
$search_name = mysqli_real_escape_string($con, $_POST['form_name']);
}
$select_name=mysqli_query($con,"SELECT * FROM test_mysql WHERE name='$search_name' ");
while($row=mysqli_fetch_array($select_name))
{
$ime=$row['name'];
$prezime=$row['lastname'];
$id_number=$row['id'];
echo $id_number." . ".$ime. " ".$prezime."<br>";
}
?>
<form action="" methom="post">
Name: <input type="text" name="form_name"/>
<input type="submit" value="send" name="go"/>
</form>
You need to move your query inside the isset() of your submit button, otherwise the code will be executed everytime the page loads causing the error.
if(isset($_POST['go']))
{
$search_name = mysqli_real_escape_string($con, $_POST['form_name']);
$select_name=mysqli_query($con,"SELECT * FROM test_mysql WHERE name='$search_name' ");
while($row=mysqli_fetch_array($select_name))
{
$ime=$row['name'];
$prezime=$row['lastname'];
$id_number=$row['id'];
echo $id_number." . ".$ime. " ".$prezime."<br>";
}
}
?>
<form action="" methom="post">
Name: <input type="text" name="form_name"/>
<input type="submit" value="send" name="go"/>
Simply, just make sure the form is submitted before building the query, you already do that but not to all the parts of the code
if(isset($_POST['go']))
{
$search_name = mysqli_real_escape_string($con, $_POST['form_name']);
$select_name=mysqli_query($con,"SELECT * FROM test_mysql WHERE name='$search_name' ");
while($row=mysqli_fetch_array($select_name))
{
$ime=$row['name'];
$prezime=$row['lastname'];
$id_number=$row['id'];
echo $id_number." . ".$ime. " ".$prezime."<br>";
}
}
This should solve it.

Query not updating not sure why

For some reason this script isn't updating the database properly according to the query. Does anybody have any idea why the script isn't updating? Please let me know!
<?php
session_start();
include '../connect.php';
if(!isset($_SESSION['id'])){
header("Location: ../index.php");
}
if(isset($_POST['submit'])){
$id=$_POST['id'];
$postid=$_POST['postid'];
$content=$_POST['content'];
$title=$_POST['title'];
echo "<pre>";
print_r($_POST);
if(!empty($content)){
$content = mysql_real_escape_string($content);
} else {
echo 'You need to write something in your comment!';
}
$upd=mysql_query("UPDATE replies SET reply_content='$content' WHERE reply_id='$postid'");
if(!$upd){
echo 'Error: '.mysql_error();
}
} else {
if (isset($_GET['id'])){
$postid = $_GET['id'];
$id=$_SESSION['id'];
$q = mysql_query("SELECT * FROM `replies` where `reply_id`='$postid'");
if(!$q){
echo 'Error: '.mysql_error();
}
$res = mysql_fetch_assoc($q);
$q2 = mysql_query("SELECT topic_subject FROM `topics` where `topic_id`='$postid'");
$res2 = mysql_fetch_assoc($q2);
if(!q2){
echo 'Error: '.mysql_error();
}
if ($res['reply_by'] == $id){
} else {
header("Location: ../pagenotfound.html");
}
}
?>
<form action="edit.php">
<input type="text" name="title" value="<?php echo $res2['topic_subject'] ?>" disabled="disabled" />
<br />
<textarea rows="20" name="content" cols="50"><?php echo $res['reply_content']?></textarea>
<input type="hidden" name="postid" value="<?php echo $postid ?>" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
<?php
}
?>
If you need more info let me know!
Update: The issue is that when I click submit, it sends me to a page which still lists the form. I noticed this isuee when I tried to print_r($_POST) because it didn't actually print $_POST, I believe there is something wrong with either the form or where it checks if isset submit.
Try with:
if(!empty($content)){
$content = mysql_real_escape_string($content);
} else {
echo 'You need to write something in your comment!';
// if $content is mandatory, you should put a die("error") here
}
You should check your $_POST array with a simple
echo "<pre>";
print_r($_POST);
and ensure that POST has vars you are looking for (first of all: submit)
EDIT: put print_r($_POST) BEFORE using it just before:
if(isset($_POST['submit'])){
ERROR: you forgot to set form method type. Try with:
<form action="edit.php" method="post">
Without that, form will send parameters as $_GET.
Here's a simple php-form tutorial. http://php.net/manual/en/tutorial.forms.php

How to disable writing to database if i made duplicate entry, and show warning in alertbox?

I am a bit new with php, so I need help. On one page i have small form with firstname and lastname fields. On submit i send it to external .php script where i want to check if there is already person with same name in database. If there is already person with entered name in database, I want to cancel writing to database, and return to the html page. I have done this, but I want to display the JS messagebox "Person with this name already exists in db!", and if the writing to base was canceled, i want my input fields show last written values. I've been reading a lot of litertaure, and I'm lost. Thanks for help anyway :)
This is my form:
<form name="form" action="write.php" method="post" onSubmit="return Validate()">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
<input type="submit">
</form>
My php code:
<?php
$con=mysqli_connect("localhost","root","","phptest");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['firstname'])) {
$firstname = $_POST['firstname'];
}
if (isset($_POST['lastname'])) {
$lastname = $_POST['lastname'];
}
$duplicate=mysqli_query($con,"SELECT * FROM persons WHERE FirstName='$firstname'");
if(mysqli_num_rows($duplicate)>0)
{
die('Name already exists' );//I want that this message shows in html file, as alert
}
else{
$sql="INSERT INTO Persons (FirstName, LastName)
VALUES('$firstname','$lastname')";
$result=mysqli_query($con,$sql);
if (!$result)
{
die('Error: ' . mysqli_error());
}
}
header( 'Location://localhost/ivanda.php' ) ;
mysqli_close($con);
?>
This line:
if(mysqli_num_rows($duplicate)>0)
{
die('Name already exists' );//I want that this message shows in html file, as alert
}
Change it to this this code:
if(mysqli_num_rows($duplicate)>0)
{
echo "<script>alert('Name already exist!!!'); </script>";
echo "<script>window.location.assign('ivanda.php'); </script>"; //add this line instead of header
}
-------------------------EDITED----------------------------------
Trys this:
$duplicate=mysqli_query($con,"SELECT * FROM Persons WHERE FirstName='$firstname' limit 1");
if(mysqli_num_rows($duplicate)>0)
{
$row = mysqli_fetch_assoc($duplicate);
echo "<script>alert('Name already exist!!!'); </script>";
echo "<script>window.location.assign('ivanda.php?firsName=".$row['FirstName']."&lastName=".$row['LastName']."'); </script>"; //add this line instead of header
}
else{
$sql="INSERT INTO Persons (FirstName, LastName)
VALUES('$firstname','$lastname')";
$result=mysqli_query($con,$sql);
if (!$result)
{
die('Error: ' . mysqli_error());
}
}
With this you are sending the var via GET on the url...then in your form you should have something like this:
<form name="form" action="write.php" method="post" onSubmit="return Validate()">
Firstname: <input type="text" name="firstname" value="<?php if(isset($_GET['firsName'])){echo $_GET['firsName'];} ?>">
Lastname: <input type="text" name="lastname" value="<?php if(isset($_GET['lastName'])) {echo $_GET['lastName'];} ?>">
<input type="submit">
</form>
PS: Go for mysqli o PDO, remember it...mysql extension is gonna be deprecated soon
Saludos.

Categories