Information don't post in database - php

I try to implement an sign in form based on webcam image, apparently, i don't errors in code, but information don't posted in database.
Here is my index with php code for insert information in database:
<?php
if (isset($_POST['desc'])) {
if (!isset($_POST['iscorrect']) || $_POST['iscorrect'] == "") {
echo "Sorry, important data to submit your question is missing. Please press back in your browser and try again and make sure you select a correct answer for the question.";
exit();
}
if (!isset($_POST['type']) || $_POST['type'] == "") {
echo "Sorry, there was an error parsing the form. Please press back in your browser and try again";
exit();
}
require_once("scripts/connect_db.php");
$name = $_POST['name'];
$email = $_POST['email'];
$name = mysqli_real_escape_string($connection, $name);
$name = strip_tags($name);
$email = mysqli_real_escape_string($connection, $email);
$email = strip_tags($email);
if (isset($_FILES['image'])) {
$name = $_FILES['image']['tmp_name'];
$image = base64_encode(
file_get_contents(
$_FILES['image']['tmp_name']
)
);
}
$sql = mysqli_query($connection, "INSERT INTO users (name,email,image) VALUES ('$name', '$email','$image')")or die(mysqli_error($connection));
header('location: index.php?msg=' . $msg . '');
$msg = 'merge';
}
?>
<?php
$msg = "";
if (isset($_GET['msg'])) {
$msg = $_GET['msg'];
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Licenta Ionut</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
<!-- font files -->
<link href='//fonts.googleapis.com/css?family=Muli:400,300' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Nunito:400,300,700' rel='stylesheet' type='text/css'>
<!-- /font files -->
<!-- css files -->
<link href="css/style.css" rel='stylesheet' type='text/css' media="all" />
<link href="web.js" rel='stylesheet' type='text/css' media="all" />
<script type="text/javascript" src="web.js"></script>
<!-- /css files -->
</head>
<body>
<p style="color:#06F;"><?php echo $msg; ?></p>
<h1>LogIn with Webcam Password</h1>
<div class="log">
<div class="content1">
<h2>Sign In Form</h2>
<form>
<input type="text" name="userid" value="USERNAME" onfocus="this.value = '';" onblur="if (this.value == '') {
this.value = 'USERNAME';
}">
<input type="password" name="psw" value="PASSWORD" onfocus="this.value = '';" onblur="if (this.value == '') {
this.value = 'PASSWORD';}">
<div class="button-row">
<input type="submit" class="sign-in" value="Sign In">
<input type="reset" class="reset" value="Reset">
<div class="clear"></div>
</div>
</form>
</div>
<div class="content2">
<h2>Register</h2>
<form action="index.php", name="index.php" method="post" enctype="multipart/form-data">
<input type="text" id="name" name="name" value="Nume">
<input type="text" id="email" name="email" value="EmailAdress">
<br>
<script type="text/javascript" src="webcam.js"></script>
<script language="JavaScript">
document.write(webcam.get_html(320, 240));
</script>
<div class="button-row">
<input class="sign-in" type=button value="Configure" onClick="webcam.configure()" class="shiva">
<input class="reset" type="submit" value="Register" id="image" onClick="take_snapshot()" class="shiva">
</div>
</form>
</div>
<div class="clear"></div>
</div>
</body>
</html>
And here is the script for connection to database:
<?php
$db_host = "localhost";
// Place the username for the MySQL database here
$db_username = "Ionut";
// Place the password for the MySQL database here
$db_pass = "1993";
// Place the name for the MySQL database here
$db_name = "users";
// Run the connection here
$connection=mysqli_connect("$db_host","$db_username","$db_pass") or die (mysqli_connect_error());
mysqli_select_db($connection,"$db_name") or die ("no database");
?>
I don't find error in code and i need your advice/help!
Thank you for interest about my problem!

To solve a problem like this, break the problem into parts.
(1) First, what is the PHP file receiving? At the top of the PHP file, insert:
<?php
echo '<pre>';
print_r($_POST);
echo '</pre>';
die('-----------------------------------');
(2) If that doesn't reveal the problem, next step is to duplicate the PHP file and in the second copy, HARD CODE the information you will be submitting at the top (replacing the PHP data that would normally be submitted):
<?php
$_POST['desc'] = 'TEST - Description';
$_POST['iscorrect'] = 'what it should be';
$_POST['type'] = 'TEST - Type';
etc
Then, run that modified file and see if the data is submitted.
(3) If that doesn't reveal the problem, keep working with the duplicate PHP file and add echo statements at various places to see where the file is breaking. For example:
$name = $_POST['name'];
$email = $_POST['email'];
$name = mysqli_real_escape_string($connection, $name);
echo 'HERE 01';
$name = strip_tags($name);
$email = mysqli_real_escape_string($connection, $email);
$email = strip_tags($email);
echo 'HERE 02';
if (isset($_FILES['image'])) {
$name = $_FILES['image']['tmp_name'];
$image = base64_encode(
file_get_contents(
$_FILES['image']['tmp_name']
)
);
}
echo 'HERE 03';
$sql = mysqli_query($connection, "INSERT INTO users (name,email,image) VALUES ('$name', '$email','$image')")or die(mysqli_error($connection));
echo 'HERE 04: $sql = ' .$sql;

Related

Submit button don't add data to MySQL

I tried to create a form which will send an email and add data to MySQL data base. For email part because I work on localhost I used formsubmit. All good but there is a conflict. When I press on send only the email is send without any data added to my database. If I delete the action attribute from form data will be added but in this case I can't send any emails. Here is my file:
<?php
require 'config.php';
if(!empty($_SESSION["id"]))
{
$id= $_SESSION["id"];
$result = mysqli_query($conn,"SELECT * FROM tb_user WHERE id= $id");
$row = mysqli_fetch_assoc($result);
}
else
{
header("Location: login.php");
}
if(isset($_POST["submit"]))
{
$name = $_POST['name'];
$email = $_POST['email'];
$cui = $_POST['cui'];
$tip = $_POST['tip'];
$adresa = $_POST['adresa'];
$query = "INSERT INTO beneficiari VALUES('','$email','$name','$cui','$tip','$adresa')";
mysqli_query($conn,$query);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Beneficiari </title>
<link rel="stylesheet" href="indexCSS.css">
<link rel="stylesheet" type="text/css" href="beneficiariCSS.css">
</head>
<body>
<div class="topnav">
Welcome <?php echo $row["name"]; ?>
Logout
<a class="active" href="index.php">Home</a>
Anunturi
Viz
Registration
</div>
<div class="container">
<form action="https://formsubmit.co/0e6b51872b4393271dbfa08bb0655fc8" method="POST">
<h3>Inregistrare</h3>
<input type="text" name="name" id="name" placeholder="Denumire institutie" required>
<input type="email" name="email" id="email" placeholder="Enter an valid email" required>
<input type="text" name="cui" id="cui" placeholder="CUI" required>
<input type="text" name="tip" id="tip" placeholder="Tipul institutie" required>
<input type="text" name="adresa" id="adresa" placeholder="Adresa" required>
<button type="submit" name="submit">Send</button>
</form>
</div>
</body>
</html>
You can remove the action from form, and add it after the SQL query, within the if statement as header, like so:
if(isset($_POST["submit"]))
{
$name = $_POST['name'];
$email = $_POST['email'];
$cui = $_POST['cui'];
$tip = $_POST['tip'];
$adresa = $_POST['adresa'];
$query = "INSERT INTO beneficiari VALUES('','$email','$name','$cui','$tip','$adresa')";
mysqli_query($conn,$query);
header('location: https://formsubmit.co/0e6b51872b4393271dbfa08bb0655fc8');
}
I believe this will work.
But whatever you do make sure you check the input!! The way you are handling your input right now is very dangerous, and allows users to inject you with SQLs (read up on SQL injections and protection)

User input textarea rendering \n\r instead of linebreak

I have a textarea element on my personal website. It is used as a comment section, when users submit information, I automatically receive an email with the data. The problem that I am having is, whenever a user inserts a line break (by pressing return) the email will render something like this:
Hello Mike,\r\n\great website\r\n\keep in touch!\r\n\
Instead of:
Hello Mike,
Great Website
keep in touch!
Here is my code, was wondering if anyone can help me! Thank you
<?php
// This connects to database
$connection = mysqli_connect ('localhost', 'username', 'password', 'database');
$message_sent = false;
function updateForm () {
global $connection;
if ( isset ($_POST['submit'])) {
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
global $connection;
$name = $_POST['name'];
$email = $_POST['email'];
$userComment = $_POST['comment'];
$name = mysqli_real_escape_string($connection, $name);
$email = mysqli_real_escape_string($connection, $email);
$userComment = mysqli_real_escape_string($connection, $userComment);
// Submits email code
$to = "michaelrivasnyc#gmail.com";
$subject = "You have a new form submission";
$body = "";
$body .= "From: ".$name. "\r\n";
$body .= "email: ".$email. "\r\n";
$body .= "message: ".($userComment). " ";
// email information going to be sent to user
$userSubject = "Thanks for submitting form.";
$userBody = "Thank you for submitting form on michaelrivas.net, we will be in touch.";
mail($to, $subject,$body);
mail($email, $userSubject, $userBody);
$message_sent = true;
} else {
$message_sent = false;
}
$name = mysqli_real_escape_string ($connection, $name);
$email = mysqli_real_escape_string ($connection, $email);
$userComment = mysqli_real_escape_string ($connection, $userComment);
$query = "INSERT INTO email (names, email, comment) ";
$query .= "VALUES ('$name' , '$email' , '$userComment') ";
$result = mysqli_query($connection, $query);
if (!$result) {
die('Connection error' . mysqli_error ());
} else {
echo "<br>" . "<br>" . "You have been added to my email list, Thanks for staying in touch";
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-126337947-3"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-126337947-3');
</script>
<!-- Icons, scripts, CSS, and other attachments. These should be the same
for all pages minus the <header> class with is the front page photo -->
<link href="images/radio-tower.png" rel="icon" type="image/x-icon"/>
<link rel="stylesheet" type="text/css" href="stylesheets/stylesheet.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="https://fonts.googleapis.com/css?family=Mina" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Timmana" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="JS/JS4web.js"></script>
</head>
<fie>
<title>Michael Rivas</title>
<!-- Top Navigation Menu -->
<div>
<div class="navBar">
<div id="myLinks">
Home
Projects
Contact
</div>
<a href="javascript:void(0);" class="icon" onclick="myFunction()">
<i class="fa fa-bars"></i>
</a>
</div>
<h1 id="textAboveForm">Keep in touch</h1>
<div id="formFields">
<form action="contactform.php" method="post" >
<input style="font-size: 16px;" id="firstnameinput" type="text" name="name" placeholder="Name" required>
<input style="font-size: 16px;" id="emailinput" type="text" name="email" placeholder= "email" required>
<br>
<textarea id="commentBox" name="comment" placeholder= "Drop a note"></textarea>
<br>
<input id="submitbutton" type="submit" name= "submit" value= "Submit">
<?php updateForm ();?>
</form>
</div>
</body>
</html>
You are misusing mysqli_real_escape_string(). It would be best that you forget this function even exists. It is the root cause of your problem. Remove it from your code and use parameterized prepared statements.
$name = $_POST['name'];
$email = $_POST['email'];
$userComment = $_POST['comment'];
// send an email
$query = "INSERT INTO email (names, email, comment) VALUES (? , ? , ?) ";
$stmt = $connection->prepare($query);
$stmt->bind_param('sss', $name, $email, $userComment);
$stmt->execute();

The data is not registered to the database

I want to make a student registration form. I get no error messages, but the data is not entered into the database.
INDEX is for INDEX NUMBER
USERNAME is for USER
EMAIL is for EMAIL
I had trouble with index variable it said that it is undefined, I am not sure if I defined the variable properly.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<!-- TemplateBeginEditable name="doctitle" -->
<title>Untitled Document</title>
<!-- TemplateEndEditable -->
<!-- TemplateBeginEditable name="head" -->
<!-- TemplateEndEditable -->
</head>
<body>
<?php
session_start();
$_SESSION["message"] = "";
$mysqli = new MySQLi("localhost","root","","accounts");
if ($_SERVER['REQUEST_METHOD'] == "POST"){
$username = $mysqli->real_escape_string($_POST["username"]);
$email = $mysqli->real_escape_string($_POST["email"]);
$index = ($_POST["email"]);
$_SESSION["username"] = $username;
$_SESSION["email"] = $email;
$sql = "INSERT INTO users (index, email, name) "
. "VALUES ('$index', '$email', '$username')";
//check if mysql query is successful
if ($mysqli->query($sql) === true)
{
$_SESSION[ 'message' ] = "Registration succesful! Added $username to the database!";
//redirect the user to welcome.php
header( "location: welcome.php" );
}
else{
$_SESSION["message"] = "user could not be added to the database";
}
}
else{
$_SESSION["message"] = "could not initiate session";
}
?>
<link href="//db.onlinewebfonts.com/c/a4e256ed67403c6ad5d43937ed48a77b?family=Core+Sans+N+W01+35+Light" rel="stylesheet" type="text/css"/>
<link rel="stylesheet" href="form.css" type="text/css">
<div class="body-content">
<div class="module">
<h1>Create an account</h1>
<form class="form" action="form.php" method="post" enctype="multipart/form-data" autocomplete="off">
<div class="alert alert-error"></div>
<input type="text" placeholder="User Name" name="username" required />
<input type="email" placeholder="Email" name="email" required />
<br>
<input type="text" placeholder="Index Number" name="index" required /><br>
<input type="submit" value="Register" name="register" class="btn btn-block btn-primary" />
</form>
</div>
</div>
</body>
</html>
Change this line :
$sql = "INSERT INTO users (index, email, name) "
. "VALUES ('$index', '$email', '$username')";
To this :
$sql = 'INSERT INTO users (index, email, name) '
. 'VALUES ("$index", "$email", "$username")';
Hope to solve your problem.

Edit form doesn't work php

Actualy was trying to solve the problem for 3 day and now have no idea what to do.
Edit form doesn't work. I have no error messages.
There is no save data file because i only output from database.
And edit.php
<?php
include_once 'config.php';
if (isset($_POST['submit'])){
if (empty($_POST['username'])){
$errors = "Впишите ваше имя";
}elseif (empty($_POST['email'])){
$errors = "Впишите ваш email";
}elseif (empty($_POST['task'])){
$errors = "Впишите задание";
}elseif (empty($_FILES['image']['name'])){
$errors = "Вставьте картинку";
}else{
$id = $_GET['edit'];
$username = mysqli_real_escape_string($db,
trim($_POST['username']));
$email = mysqli_real_escape_string($db,
trim($_POST['email']));
$task = mysqli_real_escape_string($db,
trim($_POST['task']));
$image = mysqli_real_escape_string($db,
$_FILES['image']['name']);
$target = "uploads/".basename($_FILES['image']['name']);
$sql = "UPDATE `tasks` SET `username`='$username', `email`='$email',
`task`='$task', `image`='$image' WHERE `id`='$id'";
mysqli_query($db, $sql);
move_uploaded_file($_FILES['image']['tmp_name'], $target);
$home_url = 'http://' . $_SERVER['HTTP_HOST'];
header('Location:' . $home_url);
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>задачник</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-
BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<link href="/css/style.css" rel="stylesheet">
</head>
<body>
<header>
<h3>Внесение изменений в запись</h3>
<a href="index.php" class="btn btn-default">На страницу
администратора</a>
</header>
<br>
<form method="POST" action="<?=$_SERVER['PHP_SELF'];?>" class="input_form"
enctype="multipart/form-data">
<input type="text" name="username" placeholder="Введите Имя"
class="username_input">
<input type="email" name="email" placeholder="Введите email"
class="email_input">
<br>
<br>
<input type="hidden" name="MAX_FILE_SIZE" value="300000" />
<input type="text" name="task" placeholder="Введите задание"
class="task_input">
<p>Сменить изображение</p>
<input type="file" name="image" multiple accept="image/png, image/jpeg,
image/gif">
<br>
<button type="submit" name="submit" id="add_btn">Изменить
запись</button>
</form>
I tried to var_dump($_GET('edit')); and i get the correct id of page that i want to edit, but after submit button i get redirected to index.php with no changes in db. var_dump($_POST['submit']); gives string(0), but save_task form from another folder for this proj works fine, giving string(0) after submit too.
Update query in edit.php file is not correct.
$sql = "UPDATE `tasks` SET `username`='$username', `email`='$email',`task`='$task', WHERE `id`='$id'";
Additional semicolon exists in update query before where clause.Remove it.
I think error is in $image value. debug yourself and find the error -
<?php
include_once 'config.php';
if (isset($_POST['submit'])){
echo 'form submitted? - okay <br/>';
if (empty($_POST['username'])){
$errors = "Впишите ваше имя";
}elseif (empty($_POST['email'])){
$errors = "Впишите ваш email";
}elseif (empty($_POST['task'])){
$errors = "Впишите задание";
}elseif (empty($_FILES['image']['name'])){
$errors = "Вставьте картинку";
}else{
echo 'form validated? - okay <br/>';
$id = $_GET['edit'];
$username = mysqli_real_escape_string($db,
trim($_POST['username']));
$email = mysqli_real_escape_string($db,
trim($_POST['email']));
$task = mysqli_real_escape_string($db,
trim($_POST['task']));
$image = mysqli_real_escape_string($db,
$_FILES['image']['name']);
//most probably error is here --- $_FILES['image']['name'] should gives you array!!! as you have used "multiple" in input
var_dump($_FILES, $_FILES['image'], $_FILES['image']['name']); //die('debug--');
$target = "uploads/".basename($_FILES['image']['name']);
$sql = "UPDATE `tasks` SET `username`='$username', `email`='$email',
`task`='$task', `image`='$image' WHERE `id`='$id'";
echo $sql.'<br/>' ; //copy this sql and run in phpmyadmin sql-console and check if there is any error
die('checking sql statement');
mysqli_query($db, $sql);
move_uploaded_file($_FILES['image']['tmp_name'], $target);
$home_url = 'http://' . $_SERVER['HTTP_HOST'];
//header('Location:' . $home_url);
}
}
?>
Check "action" attribute in form tag in edit.php file. action="<?=$_SERVER['PHP_SELF'];?>" .It should be action="/<?PHP echo basename($_SERVER['REQUEST_URI']); ?>".
PHP_SELF doesn't append get parameters.

php can't connect to database, display blank page

so I have this code for my form.
newuser.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400,600,700,900" rel="stylesheet" />
<link href="css/styles.css" rel="stylesheet" type="text/css" media="all" />
<link href="css/fonts.css" rel="stylesheet" type="text/css" media="all" />
<link href="css/newuser.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="page" class="container">
<div id="header">
<div id="logo">
<img src="img/minilogo.jpg" alt="" />
<h1>ADMIN</h1>
<span>PERMOHONAN DATA</span>
</div>
<div id="menu">
<ul>
<li class=""><a href="admin.php" >Home</a></li>
<li><a href="new.php" >USER</a></li>
<li><a href="#" >PENYEDIA</a></li>
<li><a href="#" >UPDATE</a></li>
<li><a href="logout.php" >LOG OUT</a></li>
</ul>
</div>
</div>
<div id="main">
<div id="banner">
<img src="img/pic01.jpg" alt="" class="image-full" />
<div id="welcome">Pendaftaran User Baru.
</div>
<div class="title">
<!--untuk form-->
<form class="form" action="submitnew.php" method="post" name="form" >
<ul><li>
</li>
</li>
<li>
<label for="name">Nama :</label>
<input type="text" name="name" required />
</li>
<li>
<label for="tel">No. Telefon:</label>
<input type="text" name="tel" required />
</li>
<li>
<label for="email">E-mail:</label>
<input type="email" name="email" placeholder="name#something.com" required />
<class="form_hint"> <script type="text/javascript">
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName("script");l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>
</li>
<li>
<label for="username">Username:</label>
<input type="text" name="username" required />
</li>
<li>
<label for="password">Password:</label>
<input type="password" name="password" required />
<!--<li>
<label for="admin">Admin</label>
<input id="radio1" name="admin" type="radio" class="radio-btn" value="admin" />
</li>-->
<li>
<button class="submit" type="submit">Create</button>
</li>
</ul>
</form>
</body>
</html>
the data will be pass through this,
submitnew.php
<?php
//debug mode
error_reporting(E_ALL);
ini_set('display_errors', '1');
//to show some error is smthng went wrong
$errors = array();
//connect to DB
$connection = mysql_connect('localhost','root','');
$db = mysql_select_db('permohonan_data',$connection);
//will run if user did submit the form
if (!empty($_POST)){
//connect sql server:
$name = $_POST['name'];
$tel = $_POST['tel'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
//no error til here
if (empty($error)){
//prevent SQL injection
$name = mysql_real_escape_string($name);
$tel = mysql_real_escape_string($tel);
$email = mysql_real_escape_string($email);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
}
//try insert value
$query = "INSERT INTO admin
(name,tel,email,username,password)
VALUES ('$name', '$tel', '$email', '$username', '$password)";
//try
if (!mysql_query($query)){
//
//die(mysql_error());
$errors[] = "Can't insert the values";
}
else {
//on success
header("Location:new.php");
exit();
}
}
?>
the problem is, it won't connect to the database neither redirect to the new.php. it will only display blank page. did I code wrong?
you have error in query(missed the ending quotes in password ):
$query = "INSERT INTO admin
(name,tel,email,username,password)
VALUES ('$name', '$tel', '$email', '$username', '$password)";
should be:
$query = "INSERT INTO admin
(name,tel,email,username,password)
VALUES ('$name', '$tel', '$email', '$username', '$password')";
and replace this:
if (empty($error)){
by
if (empty(mysql_error())){
for checking mysql error.
and instead of:
//connect to DB
$connection = mysql_connect('localhost','root','');
$db = mysql_select_db('permohonan_data',$connection);
try this:
//connect to DB
$connection = mysql_connect('localhost','root','') or die(mysql_error());
$db = mysql_select_db('permohonan_data',$connection) or die(mysql_error());
Problem is, you are using:
$errors = array();
and $error never gets a value in your code so no query executed :-)
Use this and let me know:
<?php
//debug mode
error_reporting(E_ALL);
ini_set('display_errors', '1');
//connect to DB
$connection = mysql_connect('localhost','root','');
mysql_select_db('permohonan_data',$connection);
//will run if user did submit the form
if (!empty($_POST)){
//connect sql server:
$name = $_POST['name'];
$tel = $_POST['tel'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
//prevent SQL injection
$name = mysql_real_escape_string($name);
$tel = mysql_real_escape_string($tel);
$email = mysql_real_escape_string($email);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$result = mysql_query("INSERT INTO admin (name,tel,email,username,password)
VALUES ('$name', '$tel', '$email', '$username', '$password)");
if (!empty($result)) {
// check for empty result
if (mysql_affected_rows() > 0) {
$response = $result;
$response["success"] = 0;
$response["message"] = "One row effected";
// echoing JSON response
echo json_encode($response);
} else {
// No profile found
$response["success"] = 1;
$response["message"] = "No row effected";
// echo no users JSON
echo json_encode($response);
}
} else {
// No profile found
$response["success"] = 2;
$response["message"] = "No row effected";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = -1;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>

Categories