unable to insert form datas into database - php

I need to insert all form details into database and save the uploaded image in a location. I succeeded in uploading the file to specified location. But form details are not getting inserted into database.
This is the code in pages.php
<?php
session_start();
if(!empty($_SESSION['uname']) && !empty($_SESSION['pswd'])) {
include 'classes/insert.php';
$db_con->dbcon();
$db_con->insert_data();
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['bg_img']['name']);
if(move_uploaded_file($_FILES['bg_img']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['bg_img']['name']).
" has been uploaded";
} else {
echo "There was an error uploading the file, please try again!";
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>New Page</title>
</head>
<body>
<p>Add pages</p>
logout
<br /><br />
Dashboard
<br /><br />
<form method="post" action="" enctype="multipart/form-data">
<label>Page name</label>
<input type="text" name="page_name" />
<br />
<br />
<label>Page title</label>
<input type="text" name="page_title" />
<br />
<br />
<label>Page bg img</label>
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<input type="file" name="bg_img" />
<br />
<br />
<label>Page content</label>
<textarea name="page_content"></textarea>
<br />
<br />
<input type="submit" value="Submit" name="submit" />
</form>
</body>
</html>
<?php } else {
$home_loc = 'index.php';
header ('Location:' .$home_loc);}
?>
This is the code in insert.php
class db_con {
public function dbcon() {
$hostname = 'localhost';
$username = 'root';
$pswd = 'admin';
$dbname = 'web';
mysql_connect($hostname, $username, $pswd) or die('cudn\'t connect');
mysql_select_db($dbname) or die('cudn\'t select db');
}
function insert_data() {
$this->dbcon();
if (isset($_POST['page_name']) && isset($_POST['page_title']) && isset($_POST['bg_img']) && isset($_POST['page_content'])) {
$pg_name = mysql_real_escape_string($_POST['page_name']);
$pg_title = mysql_real_escape_string($_POST['page_title']);
$pg_img = mysql_real_escape_string($_POST['bg_img']);
$pg_content = mysql_real_escape_string($_POST['page_content']);
$insert_query = mysql_query("INSERT INTO pages (page_name, page_title, page_bg_img, page_content) VALUES ('" . $pg_name . "', '" . $pg_title . "', '" . $pg_img . "', '" . $pg_content . "')");
}
}
}
$db_con = new db_con();

well, there are many things to consider.
You are mixing Javascript with PHP.
change this
var $hostname = 'myhostname';
to
$hostname = 'myhostname';
same with others.
you shouldnt make many classes in your case.
use this:
class db_con{
public function dbcon(){
.........
}
function insert_data() {
...........
}
}
you are not calling the insert_data() function
call it like that:
$insert = new insert;
$insert->insert_data();
you should escape your variables, like that:
$pg_title = mysql_real_escape_string($_POST['page_title']);
you should switch to PDO or MYSQLI.
EDIT:
try this
session_start();
if(!empty($_SESSION['uname']) && !empty($_SESSION['pswd'])){
include 'classes/insert.php';
$db_con = new db_con();
$db_con->dbcon();
$db_con->insert_data();
EDIT2:
To get the uploaded file use $_FILES instead of $_POST:
$pg_img = $_FILES['bg_img'];
change this also
and $_FILES['bg_img']['name'] != ''
instead of
&& isset($_POST['bg_img'])

Try to check if you have successfully connected to the database, If not, change your initialization from $db_con = new db_con; to $db_con = new db_con();
EDITED:
I think you should also need to change your process flow. Separate the form, the insertion process and the database connection. I suggest you create 3 separate files:
1. The Form page (HTML)
2. The process page (PHP file where you will link your form. Or where the processes will be happening)
3. The Database connection file (PHP file. Put your db connection here and other db-related functionalities).
Here's my example:
Form Page:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>New Page</title>
</head>
<body>
<p>Add pages</p>
logout
<br /><br />
Dashboard
<br /><br />
<form method="post" action="process.php" enctype="multipart/form-data">
<label>Page name</label>
<input type="text" name="page_name" />
<br />
<br />
<label>Page title</label>
<input type="text" name="page_title" />
<br />
<br />
<label>Page bg img</label>
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<input type="file" name="bg_img" />
<br />
<br />
<label>Page content</label>
<textarea name="page_content"></textarea>
<br />
<br />
<input type="submit" value="Submit" name="submit" />
</form>
</body>
</html>
As you can seee, I pointed the action of the form to process.php.
Here's my sample process.php:
<?php
include 'classes/db.php';
if(isset($_POST['submit'])){
// get your post data here
$post_data = array('your post data');
// instantiate db
$db = new Db();
// create db connection
$db_connect = $db->connect();
// check if successfully connected to db
// then call the insertion process
$db->insert_data('table_name', $post_data);
}
Then in your db.php file:
<?php
class Db {
function connect(){
$hostname = 'localhost';
$username = 'root';
$pwd = 'admin';
$dbname = 'yourdbname';
mysql_connect($hostname, $username, $pswd) or die('couldn\'t connect');
mysql_select_db($dbname) or die('couldn\'t select db');
}
function insert_data($table_name, $data) {
mysql_query("INSERT INTO ".$table_name." (page_name, page_title, page_bg_img, page_content) VALUES ($data);
}
}
?>
Just don't follow my insertion process coz I just made it short. Its just the flow I wanted to show.
Hope this helps!

Related

Submitting HTML form to PHP file

I have created two files on remote server. One is html form which asks to enter some fields and another is a php file which will get all the data and insert into the database.
For this from html file on click of submit button I am calling php file, but the file is not getting execute I think because when I click on submit it again reloads the same html page.
html :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>MCQ Questions</title>
</head>
<body>
<form method="post" >
<p> Enter the question :</p> <input name="question" type="input"> <br><br>
<p> Enter options :</p>
Enter option 1 : <input name="opt1" type="input"> <br><br>
Enter option 2 : <input name="opt2" type="input"> <br><br>
Enter option 3 : <input name="opt3" type="input"> <br><br>
Enter option 4 : <input name="opt4" type="input"> <br><br>
<p> Enter correct answer :</p>
<input name="ans" type="input"> <br><br>
<input type="submit" value = "Submit" onClick = "uploadQuestion.php">
</form>
</body>
</html>
php file:
<?php
$question=$_POST['question'];
$option1=$_POST['opt1'];
$option2=$_POST['opt2'];
$option3=$_POST['opt3'];
$option4=$_POST['opt4'];
$ans=$_POST['ans'];
$db_server = mysql_connect("address","username","pass");
if(!$db_server) {
die("Database connection failed: " . mysql_error());
}else{
$db_select = mysql_select_db("mlm",$db_server);
if (!$db_select) {
die("Database selection failed:: " . mysql_error());
}
}
$sql = "INSERT INTO questions (question,answer_a,answer_b,answer_c,answer_d,answer) VALUES ('$question','$option1',$option2,$option3,$option4,$ans)";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
?>
I also tried this way :
<input type="submit" value = "Submit" onClick = "http://address/uploadQuestion.php">
But nothing is working. Whats going wrong here? I am a beginner in web development,, can anyone help please? Thank you..
EDIT :
$database = new Database('addredd','username','pass','handbook');
$dbConnection = $database->getDB();
$stmt = $dbConnection->prepare("insert into questions(question,answer_a,answer_b,answer_c,answer_d,answer) values(?,?,?,?,?,?)");
$stmt->execute(array($question,$option1,$option2,$option3,$option4,$ans));
I tried to use pdo statement but getting this error :
Fatal error: Class 'Database' not found in /var/www/html/uploadQuestion.php on line 12
EDIT2 :
I am trying to upload one file on server and want to save it in database also, so for this I have created 2 files one is index.php and another is uploadFile.php.
As you shown now I used pdo for this but when I click on upload image again same page is getting load.
index.php
<form action="index.php" method="post" enctype="multipart/form-data">
<p> Select image to upload:</p>
<input name = "file" type="file" id="fileToUpload"><br><br>
Enter chapter name :
<input name = "chapterName" type = "text"><br><br>
<input type="submit" value = "Upload Image">
</form>
<?php
if (isset($_FILES['file']['tmp_name']))
{
$ch = curl_init();
$cfile = new CURLFile($_FILES['file']['tmp_name'],$_FILES['file']['type'],$_FILES['file']['name']);
$data = array("myfile" => $cfile);
curl_setopt($ch, CURLOPT_URL, "http://host/NewProject/uploadFile.php");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOTP_POSTFIELDS, $data);
$response = curl_exec($ch);
if($response == true)
{
echo "File posted";
}
else{
echo "Error: " . curl_error($ch);
}
}
?>
uploadFile.php
<?php
ini_set('display_errors', 1);
if(isset($_FILES['myfile']['tmp_name']))
{
$path = "files/" . $_FILES['myfile']['name'];
move_uploaded_file($_FILES['myfile']['tmp_name'], $path);
$chapterName=$_POST['chapterName'];
$dbh = new PDO('mysql:host=host;dbname=database_name','username', 'password');
$stmt = $dbh->prepare("INSERT INTO chapters (title,file) VALUES (?, ?)");
$stmt->execute(array($chapterName,$path));
if ($dbh->lastInsertId())
{
echo 'File upploaded.';
}
else
{
echo 'File could not upload.';
}
}
?>
Please help.. Thank you..
First repair your form, type="" can't be named input u can check here https://www.w3schools.com/tags/att_input_type.asp
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>MCQ Questions</title>
</head>
<body>
<form action="uploadQuestion.php" method="post" enctype="multipart/form-data">
<p> Enter the question :</p> <input name="question" type="text"> <br><br>
<p> Enter options :</p>
Enter option 1 : <input name="opt1" type="text"> <br><br>
Enter option 2 : <input name="opt2" type="text"> <br><br>
Enter option 3 : <input name="opt3" type="text"> <br><br>
Enter option 4 : <input name="opt4" type="text"> <br><br>
<p> Enter correct answer :</p>
<input name="ans" type="text"> <br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Then yours php code
<?php
// mysql connection
$db_server = mysql_connect("address","username","pass");
// check for mysql connection
if(!$db_server)
{
die("Database connection failed: " . mysql_error());
}
else
{
// check if database exists
$db_select = mysql_select_db("mlm",$db_server);
if (!$db_select)
{
die("Database selection failed:: " . mysql_error());
}
}
// escape post variables
$question = mysql_real_escape_string($_POST['question']);
$option1 = mysql_real_escape_string($_POST['opt1']);
$option2 = mysql_real_escape_string($_POST['opt2']);
$option3 = mysql_real_escape_string($_POST['opt3']);
$option4 = mysql_real_escape_string($_POST['opt4']);
$ans = mysql_real_escape_string($_POST['ans']);
// make query
$sql = "INSERT INTO questions (question,answer_a,answer_b,answer_c,answer_d,answer) VALUES ('$question', '$option1', '$option2', '$option3', '$option4', '$ans')";
// check if query runs
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
?>
Or php with mysqli
<?php
// host, username, password, database name
$db_server = mysqli_connect("address", "username", "pass", "mlm");
// check for connection
if(!$db_server)
{
die("Database connection failed: " . mysqli_error($db_server));
}
// escape post variables
$question = mysqli_real_escape_string($db_server, $_POST['question']);
$option1 = mysqli_real_escape_string($db_server, $_POST['opt1']);
$option2 = mysqli_real_escape_string($db_server, $_POST['opt2']);
$option3 = mysqli_real_escape_string($db_server, $_POST['opt3']);
$option4 = mysqli_real_escape_string($db_server, $_POST['opt4']);
$ans = mysqli_real_escape_string($db_server, $_POST['ans']);
// make query
$sql = "INSERT INTO questions (question,answer_a,answer_b,answer_c,answer_d,answer) VALUES ('$question', '$option1', '$option2', '$option3', '$option4', '$ans')";
// check if query runs
if (!mysqli_query($db_server, $sql))
{
die('Error: ' . mysqli_error($db_server));
}
?>
Or php with prepared statements
<?php
// mysql connection
$dbh = new PDO('mysql:host=adress;dbname=database_name', 'username', 'password');
// escape post variables
$question = $_POST['question'];
$option1 = $_POST['opt1'];
$option2 = $_POST['opt2'];
$option3 = $_POST['opt3'];
$option4 = $_POST['opt4'];
$ans = $_POST['ans'];
$stmt = $dbh->prepare("INSERT INTO questions (question,answer_a,answer_b,answer_c,answer_d,answer) VALUES ( ?, ?, ?, ?, ?, ?)");
$stmt->execute(array($question, $option1, $option2, $option3, $option4, $ans));
if ($dbh->lastInsertId())
{
echo 'Sucess.';
}
else
{
echo 'Fail.';
}
?>
Change your from code to this
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>MCQ Questions</title>
</head>
<body>
<form action="uploadQuestion.php" method="post" enctype="multipart/form-data">
<p> Enter the question :</p> <input name="question" type="input"> <br><br>
<p> Enter options :</p>
Enter option 1 : <input name="opt1" type="input"> <br><br> Enter option 2 : <input name="opt2" type="input"> <br><br> Enter option 3 : <input name="opt3" type="input"> <br><br> Enter option 4 : <input name="opt4" type="input"> <br><br>
<p> Enter correct answer :</p>
<input name="ans" type="input"> <br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

How to add user on a mysql server via php code?

I've created simple code that has to add user on mysql through PHP, but it doesn't. Here is the code.
<form action='' method='post'>
Login: <input type='text' name='login' /> <br/>
Pass: <input type='pass' name='pass' /> <br/>
<input type='submit'>
</form>
<?php
$c=mysql_connect('localhost','test','test');
$login=$_POST['login'];
$pass=$_POST['pass'];
$t="CREATE USER '".$login."'#'localhost' IDENTIFIED BY PASSWORD '".$pass."';";
if($login!=NULL){
if($q=mysql_query($t,$c))
{
echo "CREATED!";
}else{
die('ERROR: ' . mysql_error());
}
}
?>
Error: Password hash should be a 41-digit hexadecimal number
Whats wrong with it?
Take out the word PASSWORD. By using that keyword, it suggests you're providing the hash. dev.mysql.com/doc/refman/5.5/en/create-user.html
You want this:
$t="CREATE USER '".$login."'#'localhost' IDENTIFIED BY '".$pass."';";
Try this :
<?php
$host="localhost";
$user="root";
$password="";
$con = mysqli_connect("localhost","root","","mydb");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<!DOCTYPE html>
<head>
<title>MyExample</title>
<meta charset="UTF-8"/>
</head>
<body>
<h1>Create user in MySQL by FORM</h1>
<form action="<?php $_SERVER['PHP_SELF']?>" method="POST">
<label for="username">Username</label>
<input type="text" id="username" name="username" />
<label for="password">Password</label>
<input type="password" id="password" name="password"/>
<button type="submit" name="send">Send</button>
</form>
</body>
</html>
<?php
if (isset($_POST['send'])) {
$username = $_POST['username'];
$password = $_POST['password'];
mysqli_query($con,"CREATE USER '".$username."'#'".$host."' IDENTIFIED BY '".$password."'");
mysqli_close($con);
}
?>

mysqli_row_nums didn't work when query was given

I am creating a login page using PHP and Mysqli database, I wrote the query, however mysqli_num_rows() give me an error when value is given. PS: I did this in Object Oriented Format
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "customerdb";
$connection = #new mysqli($host, $user, $pass, $db);
if ($connection->connect_errno) {
die("Connection failed!");
exit();
}
if (isset($_POST['submit'])) {
$username = $connection->real_escape_string($_POST['username']);
$password = $connection->real_escape_string($_POST['password']);
$script = "SELECT * FROM customer_management WHERE
customer_management.Username='".$username."'AND WHERE customer_management_Password='".$password."'";
$result = $connection->query($script, MYSQLI_USE_RESULT);
$check = $result->num_rows;
if ($check >= 1){
echo "Welcome to this website";
}
else{
echo"Sorry but your input is incorrect!";
}
}
?>
<!DCOTYPE html>
<html lang='en'>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login Page</title>
</head>
<body>
<h1>Login Page</h1>
<form method="post" action="login.php">
<input type="text" placeholder = 'username' name="username" /><br /><br />
<input type="password" placeholder="password" name="password" /><br /><br />
<input type="submit" name="submit" value="Log In" />
</form>
</body>
</html>
Change customer_management_Password to customer_management.Password in your query.

Can't insert form data into database (MySQLIi)

EDIT: I'm not sure what to really say. The comments was what helped my issue out right now. I didn't remember the fact to show an error, and that was what helped me. I had pretty much just tried something that obviously wasn't working due to wrongly placed variables and such,and displaying the error code let me know what variables was the faulty ones. Thank you for all your help, and this issue is now resolved!
So long story short, the title. I have no idea why this code refuses to input the inserted data into the database, and I've tried a bunch of things that haven't resulted any better.
Connection:
<?php
session_start();
$host = 'host';
$dbusername = 'username';
$dbpassword = 'password';
$anslutning = mysqli_connect($host, $dbusername, $dbpassword) or die("<b>Could not connect to database server</b>");
$anslutning->select_db('databasename') or die("<b>Could not connect to the specified database</b>");
?>
Form to grab data from :
echo '
<h2><center>Post a topic</center></h2>
<br /><br />
<div class="indexform">
<form action="index.php" method="POST">
Title: <input type="text" name="title"> <br /> <br />
Content: <textarea name="content" class="content"> </textarea>
<br /> <br />
<input type="submit" name="postTopicOnGeneral">
</form>
</div>
';
PHP code to insert it into database
if(isset($_POST['postTopicOnGeneral'])) {
$username = $_POST['username'];
$title = $_POST['title'];
$content = $_POST['content'];
$general = $_POST['general'];
$addPostOnGeneral = $anslutning->prepare('INSERT INTO tblPosts(title, content, author, category) VALUES(?, ?, ?, ?)');
$addPostOnGeneral->bind_param("ssss", $title, $content, $username, $general);
$addPostOnGeneral->execute();
echo "<center>Post created!</center>";
sleep(2);
echo "<script> window.location.href = 'index.php?general=1' </script>";
}
Undefined index:username and Undefined:general is what I get from that.
You are bound to get that error since you are not fetching $username and $general from anywhere in your form.
Change your form this:
echo '
<h2><center>Post a topic</center></h2>
<br /><br />
<div class="indexform">
<form action="index.php" method="POST">
Title: <input type="text" name="title"> <br /> <br />
Content: <textarea name="content" class="content"> </textarea>
<br /> <br />
<input type="submit" name="postTopicOnGeneral">
</form>
</div>';
to this:
echo '
<h2><center>Post a topic</center></h2>
<br /><br />
<div class="indexform">
<form action="index.php" method="POST">
Title: <input type="text" name="title"> <br /> <br />
Content: <textarea name="content" class="content"> </textarea>
<br /> <br />
Username:
<input type="text" name="username">
General:
<input type="text" name="general">
<input type="submit" name="postTopicOnGeneral">
</form>
</div>';
And then in your index.php:
if(isset($_POST['postTopicOnGeneral'])) {
echo $username = $_POST['username'];
echo $title = $_POST['title'];
echo $content = $_POST['content'];
echo $general = $_POST['general'];
// rest of your code
Try to change
$username = $_POST['username'];
$title = $_POST['title'];
$content = $_POST['content'];
$general = $_POST['general'];
With this:
$username = isset($_POST['username']) ? $_POST['username'] : '';
$title = isset($_POST['title']) ? $_POST['title'] : '';
$content = isset($_POST['content']) ? $_POST['content'] : '';
$general = isset($_POST['general']) ? $_POST['general'] : '';

Inserting data to db in PHP

I'm trying to insert somethig to db and after i write this code i get just a blank page in php. Cam you help me ? if i delete all // i get blank page if it is as now i get imput containers
<?php
function create()
{
if(isset($_POST["submit"]))
{
$db = new mysqli('localhost', 'root', 'root', 'idoctor_db');
$username = $db->real_escape_string($_POST['username']);
$password = $db->real_escape_string($_POST['password']);
$password_conf = $db->real_escape_string($_POST['password_conf']);
$nick = $db->real_escape_string($_POST['nick']);
//create_new_user($username, $password, $password_conf, $nick);
//$db->query
//('
//INSERT INTO `idoctor_db`.`users` (`ID` ,`Login` ,`Password` ,`Name` ,`Level`)
//VALUES ('5 ' , 'kev5', 'roo5', 'kevkev5', ' 3 ' );
//');
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<link rel="stylesheet" href="css/login.css" />
</head>
<body>
<div class="container">
<form action="<?php create(); ?>" method="POST">
<input type="text" name="username" placeholder="Username..." />
<input type="password" name="password" placeholder="Password" />
<input type="password" name="password_conf" placeholder="Confirm password" />
<input type="text" name="nick" placeholder="Nick" />
<input type="submit" value="Create" name="submit"/>
</form>
</div>
</body>
</html>
If there are no errors in running this query, you will see a blank page.
All the work is happening in the background, look at your mysql table to confirm if the insert worked.
If you want to check the outcome of the query... just do the following
$outcome = $db->query
('
INSERT INTO `idoctor_db`.`users` (
`ID` ,
`Login` ,
`Password` ,
`Name` ,
`Level`
)
VALUES
(' 4 ', ' kev4 ', ' root ', ' kevkev4 ', ' 3 ');
');
if($outcome) {
echo 'success';
} else {
echo 'failed';
}
After your edit... I see another problem in your code:
<form action="<?php create(); ?>" method="POST">
<!-- ^ This is not how you submit form data to php...
action is supposed to be a URL.. however if left blank
it will take you to the same page
Try this instead:
<?php
if(isset($_POST["submit"]))
{
$db = new mysqli('localhost', 'root', 'root', 'idoctor_db');
$username = $db->real_escape_string($_POST['username']);
$password = $db->real_escape_string($_POST['password']);
$password_conf = $db->real_escape_string($_POST['password_conf']);
$nick = $db->real_escape_string($_POST['nick']);
//create_new_user($username, $password, $password_conf, $nick);
//$db->query
//('
//INSERT INTO `idoctor_db`.`users` (`ID` ,`Login` ,`Password` ,`Name` ,`Level`)
//VALUES ('5 ' , 'kev5', 'roo5', 'kevkev5', ' 3 ' );
//');
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<link rel="stylesheet" href="css/login.css" />
</head>
<body>
<div class="container">
<form method="POST">
<input type="text" name="username" placeholder="Username..." />
<input type="password" name="password" placeholder="Password" />
<input type="password" name="password_conf" placeholder="Confirm password" />
<input type="text" name="nick" placeholder="Nick" />
<input type="submit" value="Create" name="submit"/>
</form>
</div>
</body>
</html>

Categories