Unable to insert data into database with php - php

I have a problem posting data in my database with a form. Very basic stuff I'm sure but Im quite stuck :/
I am able to get stuff out of my database using the select from database routine. So I know that the connection with the databse is probably not the problem.
This is my 'upload.php':
<html>
<head>
<title>Upload</title>
</head>
<body>
<form action="action.php" method="post">
<fieldset class="first">
Name:
<input type="text" name="author" />
Heading:
<input type="text" name="heading" />
Text:
<textarea type="text" name="thecontent"> </textarea>
</fieldset>
<fieldset>
<input type="submit"/>
</fieldset>
</form>
</body>
</html>
And this is my 'action.php':
<html>
<head>
<title>Send!</title>
</head>
<body>
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
$link = mysql_connect('localhost','name','pasword')
or die ("Unable to connect");
$mydb = mysql_select_db('the_database',$link)
or die ("No database found");
$author = $_POST['author'];
$heading = $_POST['heading'];
$thecontent = $_POST['thecontent'];
$mysql_query="INSERT INTO articles ('heading', 'author', 'content')
VALUES ('$heading','$author','$thecontent')" or die(mysql_error());
echo "This was send: $author $heading $thecontent <br> ";
mysql_close()
?>
</body>
</html>
All help would be much appreciated!!
Cheers,
Ziggy
Thanks for all the help guys! I'm trying to use mysqli to insert the data however it's not yet working this is my new code in action.php:
<html>
<head>
<title>Send!</title>
</head>
<body>
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
$DB_HOST = 'localhost';
$DB_USER = '**';
$DB_PASS = '***';
$DB_NAME = '***';
# $db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if (mysqli_connect_errno()) {
echo 'Error.';
exit();
}
$author = $_POST['author'];
$heading = $_POST['heading'];
$thecontent = $_POST['thecontent'];
$query = 'INSERT INTO articles ('heading', 'author', 'content')
VALUES ('$heading','$author','$thecontent')';
$result = $db->query($query);
if ($result) {
echo $db->affected_rows."This was added.";
}
else {
echo "somethings gone very wrong.";
}
$db->close();
?>
</body>
</html>
What am I doing wrong guys?
Help is much appreciated!
Cheers,
Ziggy

You build the INSERT string, but you never call a method to realy INSERT the DB with it.
Moreover, old mysql_* methods are deprecated, use PDO or mysqli API instead, see http://www.php.net/manual/en/mysqlinfo.api.choosing.php
See also stackoverflow post about this : mysqli or PDO - what are the pros and cons?
Some PDO prepared statements examples with PDO : http://www.php.net/manual/en/pdo.prepare.php

$mysql_query="INSERT INTO articles ('heading', 'author', 'content')
 VALUES ('$heading','$author','$thecontent')";
mysql_query($mysql_query);
//required to run the query..
And mysql_close(); // missing :p

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

PHP Database: value not inserting in table

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

Trying to delete a member from the database

I am having some trouble trying to delete a member from the database I'm using, I don't think it is getting the Username correctly. Here is the form I am using for HTML
deleteForm.php
<?php
//begin our session
session_start();
?>
<html>
<head>
<title>Welcome</title>
</head>
<form action="deleteUser.php">
<p>
<center><label for="Username">Enter username to delete</center></label>
<center><input type="text" id="Username" name="Username" value="" maxlength="20" /></center>
<center><input type="submit" value="Delete Member"></center>
</p>
</form>
</body>
</html>
And this is the code to handle the deletion itself:
deleteUser.php
<?php
//begin our session
session_start();
//Check if username, password have been sent
if((!filter_input(INPUT_POST, 'Username')))
{
echo 'Please enter a valid username';
}
else
{
//Enter the valid data into the database
$memberUsername = filter_input(INPUT_POST, 'Username', FILTER_SANITIZE_STRING);
echo $memberUsername;
$SQLhostname = "****";
$SQLusername = "****";
$SQLpassword = "****";
$databaseName = "****";
try
{
echo "in the try block";
// Create connection
$conn = mysqli_connect($SQLhostname, $SQLusername, $SQLpassword)
or die("Unable to connect MySQL");
$db_selected = mysqli_select_db($conn, $databaseName)
or die("Could not select database");
$deleteMember = "DELETE FROM customers
WHERE name =
'$memberUsername'";
$result = $conn->query($deleteMember);
if(! $result ){
die('Could not delete member: ' . $conn->error);}
else{
echo "Member deleted <br/>";
}
mysqli_close($conn);
}
catch (Exception $ex)
{
//To be added
}
}
?>
The problem is it always enters the if statement and asks for a valid username which I'm assuming is not being set.
Add method attribute to your form.
<form action="deleteUser.php" method="post">
<!--^^^^^^^^^^-->
<p>
<center><label for="Username">Enter username to delete</center></label>
<center><input type="text" id="Username" name="Username" value="" maxlength="20" /></center>
<center><input type="submit" value="Delete Member"></center>
</p>
Just as a quick FYI:
Whenever a method is omitted in a form, it defaults to GET and you're using INPUT_POST therefore you should either be using INPUT_GET or add a post method, i.e: method="post".
Consult the manual:
http://php.net/manual/en/function.filter-input.php
Plus, and for your added safety, your code is open SQL injection. Do use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
in the form tag add "method" attribute:
<form ... method="POST">
In the PHP script you van find the value of inputs in the variable $_GET:
$_GET[Username'']
Kevin

PHP mysql database connect

I am trying to store data using html form into mysql database.
It is somehow not working when I click submit it should work but it seems so, But the data is not stored in my database.
Here is my php code;
<?php
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "test_database";
#mysql_connect ("$db_host","$db_username","$db_pass") or die ("Could not connect to mysql!");
#mysql_select_db ("$db_name") or die ("No Database");
$value = $_POST['input1'];
$value2 = $_POST['input2'];
$sql = "INSERT INTO 'users' ('username','pid') VALUES ('$value')('$value2')";
echo "Hello World!";
mysql_close();
?>
and here is my other php file which includes the form
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form action = "mysql_connect.php" method="post" />
<p>Input 1: <input type="text" name="input1" /> </p>
<p>Input 1: <input type="number" name="input2" /> </p>
<input type="submit" value="Submit" />
</form>
</body>
</html>
You have not executed the SQL.
$sql = "INSERT INTO 'users' ('username','pid') VALUES ('$value')('$value2')";
mysql_query($sql) or die ("Failed Executing");
echo "Hello World!";
Please use following in place of existing SQL Query your executing
$sql = mysql_query("INSERT INTO 'users' ('username','pid') VALUES ('$value', '$value2')") or die (mysql_error());
Try to replace the SQL-line with:
$sql = mysql_query("INSERT INTO 'users' ('username','pid') VALUES ('$value', '$value2')");
Your code should be:
<?php
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "test_database";
$conn=mysql_connect($db_host,$db_username,$db_pass) or die ("Could not connect to mysql!");
mysql_select_db ($db_name,$conn) or die ("No Database");
$value = $_POST['input1'];
$value2 = $_POST['input2'];
$sql = "INSERT INTO users (username,pid) VALUES ('".mysql_real_escape_string($value)."','".mysql_real_escape_string($value2)."')";
$q=mysql_query($sql);
if($q){
echo "Inserted!";
}
else
{
echo "Not inserted";
}
mysql_close();
?>
Buddy, before ask something , please research deeply.
$sql = "INSERT INTO 'users' ('username','pid') VALUES ('$value'), ('$value2')";
This will prepare insert query string.
But you need to call mysql api to insert data.
You are no executing your sql statement. Execute your sql statement, this will work for you.
if(mysql_query($sql)){ echo "Data inserted successfully."; }else{ echo "Unable to execute query." };

Connecting Php, html, and mysql

Can someone look over my code and let me know what's wrong with it?
The problem I'm having is that when I enter text to the 3 fields and hit submit, it doesn't insert to my database (mysql, with phpmyadmin as gui). No error messages or anything; it simply doesn't insert the data..
I have looked over the code over and over, and I can't pin point what's wrong with it.
//---------------------------This is my index.php------------------------------
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Web Bar Title</title>
<link rel="stylesheet" href="styles.css" type="text/css" />
</head>
<body>
<?php
if(isset($_POST['Submit']))
{
include 'connectdb.php';
include 'openconnection.php';
$first = $_POST['first'];
$second = $_POST['second'];
$third = $_POST['third'];
$query = "INSERT INTO details (first, last, third) VALUES('$first','$second','$third');";
mysql_query($query) or die('Error, insert query failed');
}
?>
<div id="page">
<tbody>
<form method="post">
<table>
<tr>
<td ><b>First</b></td>
<td><input name="first" type="text" id="first"></td>
<tr>
<tr>
<td ><b>Second</b></td>
<td><input name="second" type="text" id="second"></td>
<tr>
<td ><b>Company</b></td>
<td><input name="third" type="text" id="third" > </td>
</tr>
</table>
<input name="submit" type="submit" id="submit" value="Submit" />
</form>
</body>
</html>
</tbody>
</div>
//---------------------------------connectdb.php------------------------------------------
<?php
$dbhost = 'localhost';
$dbuser = 'sharkk';
$dbpass = 'pw';
$dbname = 'test';
?>
//---------------------------------openconnection.php-------------------------------------
<?php
$dbhost = 'localhost';
$dbuser = 'sharkk';
$dbpass = 'pw';
$dbname = 'test';
?>
<?php
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname) or die ('No Selection of Database');
?>
EDIT: It would be easier and faster to communicate via MSN/AIM/Steam/Skype, if anyone has any of those!
Change your top line to
if( isset( $_POST['submit'] ) ) {
I can't remember if it is case sensitive or not
Better still change it to
if($_SERVER['REQUEST_METHOD'] == 'POST')
The isset() method on the submit button is unreliable because Internet Explorer will not send the submit button as a post variable if the user presses the enter key to submit the form, and thus your code will not detect a form submission.
Just check MYSQL INSERT query in Your own MySQL platform, by simply copying your INSERT query and paste in your MySQL database, and check there. it wil report your fault.
If I'm right, then your problem lies on your INSERT query part. You have stated :
$query = "INSERT INTO details (first, last, third) VALUES('$first','$second','$third');";
In the above part, there shouldn't be 2 semicolons, Jus one is enough... it wil look like :
$query = "INSERT INTO details (first, last, third) VALUES('$first','$second','$third')";
Also, check ur include part too...
it shouldnt be :
include 'connectdb.php'; //braces r missing
include 'openconnection.php'; // braces r missing
it should be :
include ('connectdb.php');
include ('openconnection.php');
I hope this may do good fa U ....
CHEERS buddy.........
Try putting the values between double quotes instead of single quotes
VALUES("$first","$second","$third")

Categories