Form Data will not insert to database - php

I have connected my website to my database successfully when i submit the form it goes through but nothing is getting inserted into the database.
Code Below:
<?php
if( $_POST )
{
$con = mysql_connect("server","user","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("buycruisesdb", $con);
$users_name = $_POST['name'];
$users_email = $_POST['email'];
$users_name = mysql_real_escape_string($users_name);
$users_email = mysql_real_escape_string($users_email);
$query = "
INSERT INTO `website_subscribers`(`name_sub`, `email_sub`) VALUES ([$users_name],[$users_email])";
mysql_query($query);
echo "<h2>Thank you for subscribing!</h2>";
echo $query;
echo $users_name;
echo $users_email;
mysql_close($con);
}
?>
buycruisesdb = database
website_subscribers = table inside the database
name_sub/email_sub = columns inside the table
the form html is below:
!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form action="php/subscriber.php" id="form" method="post" name="form">
<input id="name_sub" name="name" placeholder="Name" type="text">
<input id="email_sub" name="email" placeholder="Email" type="text">
<input type="submit" value="Submit" name="f_submit">
</form>
</body>
</html>
Not sure exactly why this is not inputing anyone have an idea?
it says that it is inserting the proper values and into the proper tables
Image

Square brackets are not valid in MySQL queries. You should be using quotes around the strings.
$query = "INSERT INTO `website_subscribers` (`name_sub`, `email_sub`) VALUES ('$users_name', '$users_email')";

change it to:
$query = "
INSERT INTO website_subscribers (name_sub,email_sub) VALUES ('".$users_name."','".$users_email."') ";
just copy the code and try it out

Related

Search value from Input box in mysql php [duplicate]

This question already has answers here:
search data from html input in mysql
(2 answers)
Closed 1 year ago.
I am trying to search the username from table by using form method in HTML with submit button, and what i really want is that when user write his email address in input box and press submit, the query should echo username associated with that email address.
But the problem is that when I press search button, it is showing all the usernames on that table instead of only one. My table "payments" containing the following values: id, product id, payer_email, username, password.
My code is as under. Thanks in advance.
<?php
// Database Connection String
$con = mysql_connect($db_hostname,$db_username,$db_password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db_database, $con);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="" method="post">
Search: <input type="text" name="term" /><br />
<input type="submit" value="Submit" />
</form>
<?php
if (!empty($_REQUEST['term'])) {
$term = mysql_real_escape_string($_REQUEST['term']);
$sql = "SELECT * FROM payments WHERE payer_email LIKE '%".$term."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)){
echo 'Username: ' .$row['username'];
}
}
?>
</body>
</html>
try this
<?php
if (!empty($_REQUEST['payer_email'])) {
$term = mysql_real_escape_string($_REQUEST['payer_email']);
$sql = "SELECT * FROM payments WHERE payer_email ='{$term}'";
$r_query = mysql_query($sql);
$row = mysql_fetch_assoc($r_query)
echo 'Username: ' .$row['username'];
}
?>

PHP only adding Numbers to sql in column of VARCHAR

PHP only adding Numbers to MySQL in column of VARCHAR instead of texts
when using query directly in MySQL it works...but if I use $_POST from HTML, IT fails
I don't know the reason how it is getting failed. what is the problem here ?
<?php
$link=mysqli_connect("localhost","root","","home_ac");
if(mysqli_connect_error()) {
die("error in database");
}
$name =$_POST["name"];
$query = "INSERT INTO `test`(`number`, `name`) VALUES (NULL,$name)";
if(mysqli_query($link, $query)){
echo "done";
}
else {
echo "failed";
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form method="post">
<input type="text" placeholder="enter a name" name="name">
<input type="submit" value="add">
</form>
</body>
</html>
You need quotes around text
$query = "INSERT INTO `test`(`number`, `name`) VALUES (NULL,'$name')";
Please, think about prepared query. It solve quotes problem and protect from SQL injection.
You have to use PHP Prepared Statements or PHP Data Objects (PDO).
For example, using PDO:
<html>
<head>
<meta charset="utf-8">
<title> Example PDO Insert </title>
</head>
<body>
<form method="post" action="" name="myForm" id="myForm">
<input type="text" placeholder="Enter Your Name" name="name" required="required">
<input type="submit" name="submit" value="add">
</form>
</body>
</html>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "home_ac";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ( isset($_POST['submit']) && !empty($_POST['name']) ) {
# code...
$sql = "INSERT INTO test (number,name) VALUES (NULL,'$name')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>

How to pass form data to another page and database both?

Actually i'm trying to create a table by name that user suggests and insert data into that table, also by user's suggestion.
I've two php files: CreateTable.php and EnterData.php
Here is my code of CreateTable.php:
<?php
$conn = new mysqli("localhost","root","","mywebsite");
if (isset($_POST['tbButton'])) {
$qry = "Create Table ".$_POST['tableName']."(firstname varchar(25),lastname varchar(25));";
$res = mysqli_query($conn,$qry);
if ($res) {
echo "Table Created!";
}
else{
die("query failed!");
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Create Table</title>
</head>
<body>
<form action="EnterData.php" method="post">
<p><input type="text" name="tableName" placeholder="Enter Table Name..."></p>
<p><input type="submit" name="tbButton"></p>
</form>
</body>
</html>
Here is my code of EnterData.php:
<?php
$tbname = $_POST['tableName'];
$conn = new mysqli("localhost","root","","mywebsite");
if (isset($_POST['dataButton'])) {
$qry = "Insert into ".$tbname."(firstname,lastname) values('".$_POST['firstname']."','".$_POST['lastname']."');";
$res = mysqli_query($conn,$qry);
if ($res) {
echo "Data Inserted!";
}
else{
die("query failed!");
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Create Table</title>
</head>
<body>
<form action="" method="post">
<p><input type="text" name="firstname" placeholder="Enter First Name..."></p>
<p><input type="text" name="lastname" placeholder="Enter Last Name..."></p>
<p><input type="submit" name="dataButton"></p>
</form>
</body>
</html>
Problem is that when I write action="EnterData.php" Table doesn't create in database but form values passes to 'EnterData' file.
and when I write action="CreateTable.php" table is created in database but values doesn't pass to 'EnterData' file.
I want to pass values to EnterData file and database too.
this my first attempt on stackoverflow, hope i explained my question very nicely
You can pass your tablename through get method
CreateTable.php
<?php
$conn = new mysqli("localhost","root","","mywebsite");
$tableName = $_POST['tableName'];
if (isset($_POST['tbButton'])) {
$qry = "Create Table ".$tableName ."(firstname varchar(25),lastname varchar(25));";
$res = mysqli_query($conn,$qry);
if ($res) {
header("Location: EnterData.php?tableName=".$tableName);
}
else{
die("query failed!");
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Create Table</title>
</head>
<body>
<form action="CreateTable.php" method="post">
<p><input type="text" name="tableName" placeholder="Enter Table Name..."></p>
<p><input type="submit" name="tbButton"></p>
</form>
</body>
</html>
EnterData.php
<?php
$tbname = $_GET['tableName'];
$conn = new mysqli("localhost","root","","mywebsite");
if (isset($_POST['dataButton'])) {
$qry = "Insert into ".$tbname."(firstname,lastname) values('".$_POST['firstname']."','".$_POST['lastname']."');";
$res = mysqli_query($conn,$qry);
if ($res) {
echo "Data Inserted!";
}
else{
die("query failed!");
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Create Table</title>
</head>
<body>
<form action="EnterData.php?tableName=<?php echo $tbname;?>" method="post">
<p><input type="text" name="firstname" placeholder="Enter First Name..."></p>
<p><input type="text" name="lastname" placeholder="Enter Last Name..."></p>
<p><input type="submit" name="dataButton"></p>
</form>
</body>
</html>
Why would you let the user create tables in your database in the first place (with root privileges!)?
As for your question... Both php files submit to EnterData.php (that is if EnterData.php's blank action attribute is properly interpreted by the browser), so your CreateTable.php has no idea of what $_POST['tableName'] is.
I don't know what it is you are trying to do, but php files don't magically get to know each other's variables - you actually have to include a file in another one to let them share a set of variables, pass the variables through $_REQUEST or use AJAX to take care of things.
I would personally recommend using uppercase for GET and POST whenever possible.

can't get connection with sqlite DB

I am quite familiar with PHP and mySQL. But for a change, I wanted to use sqlite as a DB, I just can't get the connection right. I have been following the 2. code example from this website, so my code looks like this:
<html>
<head>
<title>
DB bearbeiten
</title>
</head>
<body>
<form action="insert.php" method="post">
<input type="text" name="name" placeholder="Name">
<input type="text" name="eName" placeholder="E-Number">
<input type="text" name="causes" placeholder="Wirkung">
<input type="number" name="danger" placeholder="Gefahreinstufung">
<button type="submit" name="submit">Eintragen</button>
</form>
<?php
echo '1';
if(isset($_POST['submit'])){
echo '2';
$table = "zusatzstoffe";
$filename = "sqlite:/data/Adrian/zusatzstoffe.db";
$db = new PDO($filename) or die("cannot open DB");
//$db = SQLite3::_construct();
settype($danger, "integer");
$name = $_POST['name'];
$eName = $_POST['eName'];
$causes = $_POST['causes'];
$danger = $_POST['danger'];
$db->exec("INSERT INTO $table (name, number, causes, danger) VALUES ($name, $eName, $causes, $danger)");
}
?>
</body>
</html>
This line doesn't work, I just don't know why: $db = new PDO(filename, '','') or die("can not open DB");:

Using PHP to pull data from Access Database PHP Warning: odbc_fetch_array(): 4 is not a valid ODBC result resource in EditRecord.php on line 91

I'm trying to create a set of webpages that work together to allow users to view, delete, and edit rows of a MS Access database using PHP.
Membership.php shows a list of the names of members in the Access database. Their names are also hyperlinks that, when clicked, take users to another page EditRecord.php where all of information on the member whose name was clicked on Membership.php is displayed in text boxes with the option to completely delete the record, or just update certain fields.
Membership.php and EditRecord.php are displayed below. The error code is for line 91 of my source for EditRecord.php, but I cut some things out of this post for privacy. Instead, the line has been marked like so:
//--------This is the error line----------
code
[Membership.php]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="Accounts.css">
<style type="text/javascript" src="Validate.js"></style>
<style type="text/javascript" scr="Redirect.js"></style>
<style type="text/javascript" src="Utilities.js"></style>
<title>Member Information Input</title>
</head>
<body>
<div id="content">
<?php
//Establish data connection using external file
require("connection.php");
//Issue SQL SELECT Statement
$sql = "SELECT * FROM Membership";
//Stores any results that match the search term.
$rs = odbc_exec($conn, $sql);
//Set counter for search results to zero
$results = 0;
//Iterates through search results and prints information on records that match
while($row = odbc_fetch_array($rs))
{
$results += 1;
echo '<p>' . $row['FirstName'] . " " . $row['LastName'] . "</p>";
}
?>
</div>
</body>
</html>
[EditRecord.php]
<?php
//Retrieve ID value - if the page is loading for the first time, use $_GET[]. If the
//delete or edit button has been clicked, use $_POST[]
if (isset($_GET['ID'])) {
$userID = $_GET['ID'];
}
else {
$userID=$_POST['ID'];
}
//Establish data connection
require("connection.php");
//If the Delete Button is clicked
if (isset($_POST['DelBtn'])) {
//Issue SQL Statement to Delete Selected Record
$sqlDelete = "DELETE FROM Membership WHERE ID = $userID";
//Execute the SQL Delete Query
$rsDelete = odbc_exec($conn,$sqlDelete);
if(odbc_num_rows($rsDelete) == 1) {
echo "Record successfully deleted!";
}
}
//If the Edit Button is clicked
else if (isset($_POST['EditBtn'])) {
//Collect form field values in scalar variables
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];
$Address = $_POST['Address'];
$City = $_POST['City'];
$State = $_POST['State'];
$Email = $_POST['Email'];
$Gender = $_POST['Gender'];
$Comments = $_POST['Comments'];
//Issue SQL Statement to Update Selected Record
$sqlUpdate = "UPDATE Membership SET FirstName = '$FirstName', LastName = '$LastName', Address = '$Address', City = '$City', State = '$State'" .
"Email='$Email', Gender = '$Gender', Comments = '$Comments' WHERE ID = $userID";
//Execute the SQL UPDATE Query
$rsEdit = odbc_exec($conn,$sqlUpdate);
if(odbc_num_rows($rsEdit) == 1) {
echo "Record successfully updated!";
}
}
//Issue SQL SELECT Statement to Select Record to Edit or Delete
$sql = "SELECT * FROM Membership WHERE ID = $userID";
//Execute the SQL Query
$rs = odbc_exec($conn, $sql);
odbc_close($conn);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="Accounts.css">
<style type="text/javascript" src="Validate.js"></style>
<style type="text/javascript" src="Utilities.js"></style>
<title>Member Information Input</title>
</head>
<body>
<div id="content">
<form method="post" action="EditMember.php" name="EditForm">
<?php
// Loop through and display the recordset returned by SELECT statement. Display the record values in HTML Text Boxes
**//--------This is the error line----------
while ($row = odbc_fetch_array($rs)) {
?>**
First Name: <input type="text" name="FirstName" value="<?php echo $row['FirstName']?>"><br>
Last Name: <input type="text" name="LastName" value="<?php echo $row['LastName']?>"><br>
Address: <input type="text" name="Address" value="<?php echo $row['Address']?>"><br>
City: <input type="text" name="Telephone" value="<?php echo $row['City']?>"><br>
State: <input type="text" name="Telephone" value="<?php echo $row['State']?>"><br>
Email: <input type="text" name="Email" value="<?php echo $row['Email']?>"><br>
Gender: <input type="text" name="Telephone" value="<?php echo $row['Gender']?>"><br>
Comments: <input type="text" name="Comments" value="<?php echo $row['Comments']?>"><br><br>
<input type="hidden" name="ID" value="<?php echo $row['ID']?>" >
<?php
}
?>
<input type="submit" name="EditBtn" value="Edit Record"> <input type="submit" name="DelBtn" value="Delete Record">
</form>
</div>
<div id="footer">
<?php require("Footer.php"); ?>
</div>
</body>
</html>
I also find this strange, because there are five records in my database, not four. Is that because it starts counting at zero?
Any insight or advice would be greatly appreciated.
Your problem is that you are calling odbc_close() and closing the connection before your loop calls odbc_fetch_array(). You need to leave the connection open until after you've fetched all of the rows.
Also, the "4" in the error message does not refer to a number of rows or anything like that; it's just the numeric representation of result identifier for the resource created by the odbc_exec() call.

Categories