PHP Database: value not inserting in table - php

insert.php
<?php
mysql_connect("localhost","root",""); mysql_select_db("basic");
$name=$_POST['fname'];
$twait=$_POST['twait'];
$cprice=$_POST['cprice'];
$dprice=$_POST['dprice'];
$order= "INSERT INTO calculator
(name,total_wt,crt_price,dollar_rate) VALUES
('$name','$twait','$cprice','$dprice')";
$result = mysql_query('$order');
echo "Done";
?>
HTML page:
<!DOCTYPE html>
<html>
<head>
<title>JN DIAMONDS</title>
</head>
<body>
<form align="center" method="POST" action="insert.php">
<fieldset>
<legend>Info</legend><br>
<input type="text" name="fname" placeholder="Name"><br><br>
<input type="text" name="twait" placeholder="Total Rough Weight"><br><br>
<input type="text" name="cprice" placeholder="1 Carat Price"><br><br>
<input type="text" name="dprice" placeholder="Dollar Rate"><br><br>
<input type="submit" name="submit"value="Submit"><br>
</fieldset>
</form>
</body>
</html>

$order is a variable containing your mysql string.
When you put $order in quotes, then you are not sending $order into the mysql string, you are actually trying to execute the query '$order' which is not a valid mysql query.
Simply remove the quotes.
$result = mysql_query($order);

The actual error in your code has already been pointed out.
The mysql_* extension is deprecated and will be removed in the upcoming version 7 of php; choose another api to connect to your MySQL server, e.g. PDO. Using prepared statements will take care of the worst sql injections as well.
<?php
if ( !isset($_POST['fname'], $_POST['twait'], $_POST['cprice'], $_POST['dprice']) ) {
trigger_error('missing POST parameter in '.var_export($_POST, true), E_USER_WARNING);
echo '<html><head><title>...</title><body><h1>missing POST parameter</h1></body></html>';
}
else {
$pdo = new PDO('mysql:host=localhost;dbname=basic;charset=utf8', 'root', '', array(
PDO::ATTR_EMULATE_PREPARES=>false,
PDO::MYSQL_ATTR_DIRECT_QUERY=>false,
PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));
$stmt = $pdo->prepare('
INSERT INTO
calculator
(name,total_wt,crt_price,dollar_rate)
VALUES
(:fname,:twait,:cprice,:dprice)
');
$stmt->execute(array(
'fname'=>$_POST['fname'],
'twait'=>$_POST['twait'],
'cprice'=>$_POST['cprice'],
'dprice'=>$_POST['dprice']
));
echo "Done";
}

Pls try this code
<?php
mysql_connect("localhost","root",""); mysql_select_db("basic");
$name=$_POST['fname'];
$twait=$_POST['twait'];
$cprice=$_POST['cprice'];
$dprice=$_POST['dprice'];
$order= "INSERT INTO calculator
(name,total_wt,crt_price,dollar_rate) VALUES
('$name','$twait','$cprice','$dprice')";
$result = mysql_query($order);
echo "Done";
?>

Use mysqli instead of mysql.
$con = mysqli_connect('localhost', 'root', '', 'basic');
$name=$_POST['fname'];
$twait=$_POST['twait'];
$cprice=$_POST['cprice'];
$dprice=$_POST['dprice'];
$order= "INSERT INTO `calculator` (name,total_wt,crt_price,dollar_rate)
VALUES ('".$name."','".$twait."','".$cprice."','".$dprice."')";
$result = mysqli_query($con,$order);
echo "Done";

Related

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;
?>

Am I using PDO correctly to prevent sql injections?

I've spent the last day trying to figure out how to incorporate PDO into my code to prevent sql injections. This is what I have come up with. However, whenever I submit my information from the browser, it is not updated into my table and no error messages are shown. Something is wrong but I'm not sure what. I'm postive the syntax is not the problem because I've checked that multiple times. I know my database can be accessed so I'm thinking there is a problem with the way I'm using PDO. Please help me guys.
The PSBE_LOGIN contains all the information to access my database
<?php
require_once 'PSBE_LOGIN.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL:" . mysql_error());
mysql_select_db($db_database, $db_server)
or die("Unable to select database:" . mysql_error());
if (isset($_POST['title']) &&
isset($_POST['author']) &&
isset($_POST['isbn']))
//This checks to see if there is a value inputted into the form at the bottom
{
$title = get_post('title');
$author = get_post('author');
$isbn = get_post('isbn');
//This retrieves information from the user and assigns it to a variable
$stmt = $pdo->prepare('INSERT INTO classifieds(title, author, isbn)
. VALUES(:title, :author, :isbn)');
$stmt->execute(array('title'=> $title, 'author'=> $author, 'isbn' => $isbn));
}
echo <<<_END
<form action="PSBE_POST_AD.php" method="post">
Title <input type="text" name="title" />
Author <input type="text" name="author" />
ISBN <input type="text" name="isbn" />
<input type="submit" value="ADD RECORD" />
</form>
_END;
?>
EDIT: CODE REWRITTEN TO INCLUDE PDO API.
<?php
require_once'connection.php';
$db = new PDO('mysql:host='.$db_host.';dbname='.$db_name,$db_username,$db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
if (isset($_POST['title']) &&
isset($_POST['author']) &&
isset($_POST['isbn']))
//This checks to see if there is a value inputted into the form at the bottom
{
$title = get_post('title');
$author = get_post('author');
$isbn = get_post('isbn');
//This retrieves information from the user and assigns it to a variable
$stmt = $pdo->prepare('INSERT INTO classifieds(title, author, isbn)
. VALUES(:title, :author, :isbn)');
$stmt->execute(array('title'=> $title, 'author'=> $author, 'isbn' => $isbn));
}
echo <<<_END
<form action="PSBE_POST_AD.php" method="post">
Title <input type="text" name="title" />
Author <input type="text" name="author" />
ISBN <input type="text" name="isbn" />
<input type="submit" value="ADD RECORD" />
</form>
_END;
function get_post($var){
return mysql_real_escape_string($_POST[$var]);
}
?>
Get rid of both
$title = get_post('title');
$author = get_post('author');
$isbn = get_post('isbn');
and
function get_post($var){
return mysql_real_escape_string($_POST[$var]);
}
because the function you're using is based on an mysql_ function and those two APIs do not mix.
You don't need it, because you're already using placeholders.
while replacing it with
$title = $_POST['title'];
$author = $_POST['author'];
$isbn = $_POST['isbn'];
You also need to change
$stmt = $pdo->prepare(...
to
$stmt = $db->prepare(...
given your PDO connection $db = new PDO(...
You are not using them correctly. You need to connect using the PDO API (you're connecting using the mysql_ API). Otherwise, the preparation is correct.

how to fetch data from mysql and write it to innerhtml of a div in PHP

Apologies for the newbie question, I just started with PHP, trying to fetch data when the user writes ID, and get info from database and write it into innerhtml of div's inside the form. How can I do it? thanks.
<form action="read.php" method="post">
Bring Data of ID <input type="text" name="id" />
<br/>
<input type="submit" />
<br/>
<div id="username" style="font-weight:bold;" /></div>
<br/>
<div id="email" style="font-weight:bold;" /></div>
<br/>
<div id="password" style="font-weight:bold;" /></div>
</form>
<?php
$db_username = "root";
$db_password = "";
$con = new PDO('mysql:host=localhost;dbname=test', $db_username, $db_password);
if (!$con) {
echo "error";
}
else {
echo "connected";
}
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$query = $con->prepare(" SELECT * FROM bucky (username, email, password) WHERE id=:id ");
$query->execute(array(
':id' => $_POST['id']
));
}
else {
die("Die hacker!");
}
In your read.html, append your html code at the end:
<?php
[...]
$query = $con->prepare(" SELECT * FROM bucky (username, email, password) WHERE id=:id ");
$query->execute(array(
':id' => $_POST['id']
));
$result = $sth->fetchAll();
}
else {
die("Die hacker!"); // seriously?
}
?><html><body><?php
print_r($result); ?>
</body></html>
This will print you the result of your query.
You can also iterate over the result, but i think you should really just read the documentation on PDO and how to use it. Maybe a simple introduction to PHP as well. This is a VERY basic Question.

Getting items from a database not working as expected

I'm learning PHP and I've hit a wall.
When the user submits to the form, it adds to the database.
I am also trying to display all items in the database on the same page as the form.
However,this only works if the form has just been submitted. If the form has not been submitted (but there is still content in the database), nothing is shown.
How can I always show what is in the current database?
<form action="" method="post">
<input type="text" name="todo_content" id="">
<input type="submit" value="Submit">
</form>
<?php
if ( isset($_POST['todo_content'])) {
$latest_content = $_POST['todo_content'];
} else {
die();
}
$todo_db = mysqli_connect('localhost', 'root', 'root');
mysqli_select_db($todo_db, 'todo_list');
mysqli_query(
$todo_db,
"INSERT INTO todo_items (item_content) VALUES ('$latest_content')"
);
$all_todos = mysqli_query( $todo_db, "SELECT item_content FROM todo_items" );
$all_todos_result = mysqli_fetch_array($all_todos);
var_dump($all_todos_result); // these show nothing
var_dump($all_todos); // these show nothing
?>
The die() is your problem:
if ( isset($_POST['todo_content'])) {
echo 'is set';
$latest_content = $_POST['todo_content'];
} else {
die();
}
If $_POST is not set, you will never reach the part where you start printing your items. And since the form is not submitted, $_POST is empty.
EDIT
You could do it like this:
<form action="" method="post">
<input type="text" name="todo_content" id="">
<input type="submit" value="Submit">
</form>
<?php
$todo_db = mysqli_connect('localhost', 'root', 'root');
mysqli_select_db($todo_db, 'todo_list');
if ( isset($_POST['todo_content'])) {
$latest_content = $_POST['todo_content'];
mysqli_query($todo_db, "INSERT INTO todo_items (item_content) VALUES ('$latest_content')");
}
$all_todos = mysqli_query( $todo_db, "SELECT item_content FROM todo_items" );
$all_todos_result = mysqli_fetch_array($all_todos);
var_dump($all_todos_result); // these show nothing
var_dump($all_todos); // these show nothing
?>
You need to move your insert query inside your if condition and you will need not to die if the form is not submitted but print the form and your query results
$todo_db = mysqli_connect('localhost', 'root', 'root');
mysqli_select_db($todo_db, 'todo_list');
if ( isset($_POST['todo_content'])) {
echo 'is set';
$latest_content = $_POST['todo_content'];
mysqli_query($todo_db, "INSERT INTO todo_items (item_content) VALUES ('$latest_content')");
} else {
?>
<form action="" method="post">
<input type="text" name="todo_content" id="">
<input type="submit" value="Submit">
</form>
<?php
$all_todos = mysqli_query( $todo_db, "SELECT item_content FROM todo_items" );
$all_todos_result = mysqli_fetch_array($all_todos);
var_dump($all_todos_result);
var_dump($all_todos);
}
As side note i'd say you are at high risk of mysql injection. You should use prepaed statments and not inserting $_POST data inside your database directly

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.

Categories