Basically I want to send the same message to several recipients and I want it to register with a checkbox if the email was sent to that user or unchecked if it wasn't(The user has to check the checkbox so it registers) and I can't find a way so when a user checks a checkbox it gets updated in the database. I've tried with Ajax but I've no idea how to properly use it. I need some serious help.
My index.php
<?php
include_once 'dbh.php';
include_once 'contact.php';
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="/css/reset.css">
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<br>
<div class="tabela">
<table class="scroll">
<thead>
<tr>
<th>                        
                            
          Nome da Escola                 
                           
          </th>
<th>              Email Geral da Escola         
        </th>
<th>   Enviado</th>
</tr>
</thead>
<tbody>
<?php
$execItems = $conn->query("SELECT Nome,EmailGeral,Enviado FROM escolas");
while($infoItems = $execItems->fetch_array()){
echo "
<tr>
<td>".$infoItems['Nome']."</td>
<td>".$infoItems['EmailGeral']."</td>
<td><input type=\"checkbox\"".($infoItems['Enviado']?' checked':'checked')."\" /></td>
</tr>
";
}
?>
</tbody>
</table>
<div class="mail">
<form action="" method="post">
<button class="butao" type="button" onclick="emailNext();">Adicionar Email</button>
<div id="addEmail"></div>
<script>
function emailNext() {
var nextEmail, inside_where;
nextEmail = document.createElement('input');
nextEmail.type = 'text';
nextEmail.name = 'email[]';
nextEmail.className = 'insemail';
nextEmail.style.display = 'inline-block';
nextEmail.placeholder = 'Insira o Email';
inside_where = document.getElementById('addEmail');
inside_where.appendChild(nextEmail);
return false;
}
</script>
Assunto:<br><textarea rows="1" name="subject" cols="30"></textarea><br>
Mensagem:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input class="butao" type="submit" name="submit" value="Submit">
</form>
</div>
</div>
</body>
</html>
Here's the connection to the database that I've created:
<?php
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "escoladb";
$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
if (mysqli_connect_errno())
{
echo "can't connect to MySQL: " . mysqli_connect_error();
}
?>
And finally the contact so I can send emails to the schools that I want:
<?php
if(isset($_POST['submit'])){
$to = implode(',', $_POST['email']);;
$from = "g.afonso.escola#gmail.com";
$subject = $_POST['subject'];
$message = $_POST['message'];
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "<div style=\"font-size:25px;background-color:white;text-align:center;\"> Email Enviado </div>";
}
?>
Related
hi guys how can i create a validation so that when i import a csv file it will not give me a error offset(intentionally reduced the csv file column)
i got the code https://www.webslesson.info/2016/10/import-csv-file-data-into-mysql-database-using-php-ajax.html
here is the code in index.php
<?php
$connect = mysqli_connect("localhost", "root", "", "db");
$query = "SELECT * FROM tbl_employee ORDER BY id desc";
$result = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Webslesson Tutorial | Import CSV File Data into MySQL Database using PHP & Ajax</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<br /><br />
<div class="container" style="width:900px;">
<h2 align="center">Import CSV File Data into MySQL Database using PHP & Ajax</h2>
<h3 align="center">Employee Data</h3><br />
<form id="upload_csv" method="post" enctype="multipart/form-data">
<div class="col-md-3">
<br />
<label>Add More Data</label>
</div>
<div class="col-md-4">
<input type="file" name="employee_file" style="margin-top:15px;" accept=".csv"/>
</div>
<div class="col-md-5">
<input type="submit" name="upload" id="upload" value="Upload" style="margin-top:10px;" class="btn btn-info" />
</div>
<div style="clear:both"></div>
</form>
<br /><br /><br />
<div class="table-responsive" id="employee_table">
<table class="table table-bordered">
<tr>
<th width="5%">ID</th>
<th width="25%">Name</th>
<th width="35%">Address</th>
<th width="10%">Gender</th>
<th width="20%">Designation</th>
<th width="5%">Age</th>
</tr>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row["id"]; ?></td>
<td><?php echo $row["name"]; ?></td>
<td><?php echo $row["address"]; ?></td>
<td><?php echo $row["gender"]; ?></td>
<td><?php echo $row["designation"]; ?></td>
<td><?php echo $row["age"]; ?></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#upload_csv').on("submit", function(e){
e.preventDefault(); //form will not submitted
$.ajax({
url:"import.php",
method:"POST",
data:new FormData(this),
contentType:false, // The content type used when sending data to the server.
cache:false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data){
if(data=='Error1')
{
alert("Invalid File");
}
else if(data == "Error2")
{
alert("Please Select File");
}
else if(data != 'Error1' && data != 'Error2')
{
$('#employee_table').html(data);
alert("Data Import Successfully");
}
}
})
});
});
</script>
and here is for import.php
<?php
if(!empty($_FILES["employee_file"]["name"]))
{
$connect = mysqli_connect("localhost", "root", "", "db");
$output = '';
$allowed_ext = array("csv");
$tmp = explode(".", $_FILES["employee_file"]["name"]);
$extension = end($tmp);
if(in_array($extension, $allowed_ext))
{
$file_data = fopen($_FILES["employee_file"]["tmp_name"], 'r');
fgetcsv($file_data);
while($row = fgetcsv($file_data))
{
$id = mysqli_real_escape_string($connect, $row[0]);
$name = mysqli_real_escape_string($connect, $row[1]);
$address = mysqli_real_escape_string($connect, $row[2]);
$gender = mysqli_real_escape_string($connect, $row[3]);
$designation = mysqli_real_escape_string($connect, $row[4]);
$age = mysqli_real_escape_string($connect, $row[5]);
$query = "
INSERT INTO tbl_employee
(id,name, address, gender, designation, age)
VALUES ('$id','$name', '$address', '$gender', '$designation', '$age')
";
mysqli_query($connect, $query);
}
$select = "SELECT * FROM tbl_employee ORDER BY id DESC";
$result = mysqli_query($connect, $select);
$output .= '
<table class="table table-bordered">
<tr>
<th width="5%">ID</th>
<th width="25%">Name</th>
<th width="35%">Address</th>
<th width="10%">Gender</th>
<th width="20%">Designation</th>
<th width="5%">Age</th>
</tr>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["id"].'</td>
<td>'.$row["name"].'</td>
<td>'.$row["address"].'</td>
<td>'.$row["gender"].'</td>
<td>'.$row["designation"].'</td>
<td>'.$row["age"].'</td>
</tr>
';
}
$output .= '</table>';
echo $output;
}
else
{
echo 'Error1';
}
}
else
{
echo "Error2";
}
?>
i put all the code so that every one can try it too.
Thanks for answer
Objective Inserting name(input-text) and info(textarea-contains multiple lines) into the database, and after submission of the form, at the same page, 2 columns are for displaying the same data in columns, name & info, but under info column. I have made buttons for each row in front of the names, which is used as slideToggle for showing/hiding which contains the data retrieved from the 'info' column
Problem - when I am clicking the button of 1st row, instead of displaying the info related to 1st entry only, it is sliding and showing all info(s) related to all entries at only click.
*others - one more input has been added to the form but as hidden used for id(auto increment)
----index.php-----
<?php include('php_code.php'); ?>
<?php
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$update = true;
$record = mysqli_query($db, "SELECT * FROM records WHERE id=$id");
if (count($record) == 1 ) {
$n = mysqli_fetch_array($record);
$name = $n['name'];
$acc = $n['acc_no'];
$info = $n['info'];
}
}
?>
<html>
<head>
<title>JSK</title>
<link rel="stylesheet" href="style.css" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('form').hide();
$('p').hide();
$('#sp').hide();
$("#inf").click(function(){
$("p").slideToggle();
$('#sp').slideToggle();
});
$("#fo").click(function(){
$("form").slideToggle();
});
});
</script>
</head>
<body>
<div class="container">
<div class="left">
<?php if (isset($_SESSION['message'])): ?>
<div class="msg">
<?php
echo $_SESSION['message'];
unset($_SESSION['message']);
?>
</div>
<?php endif ?>
<?php $results = mysqli_query($db, "SELECT * FROM records"); ?>
<table>
<thead>
<tr>
<th>Name</th>
<th>Account No</th>
<th>Info</th>
<th colspan="2">Action</th>
</tr>
</thead>
<?php while ($row = mysqli_fetch_array($results)) { ?>
<tr>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['acc_no']; ?></td>
<td><button id="inf" onclick="myFunction()">show</button></td>
<td>
<a href="index.php?edit=<?php echo $row['id']; ?>" class="edit_btn" >Edit</a>
</td>
<td>
Delete
</td>
</tr>
<tr id="sp"> <td colspan="4"><p> <?php echo $row['info']; ?> </p></td>
</tr>
<?php } ?>
</table>
<div id="fotable" align="center">
<button id="fo">Add New/Edit</button>
</div>
<form method="post" action="php_code.php" >
<input type="hidden" name="id" value="<?php echo $id; ?>">
<div class="input-group">
<label>Name</label>
<input type="text" autocomplete="off" name="name" value="<?php echo $name; ?>">
</div>
<div class="input-group">
<label>Account No</label>
<input type="text" name="acc" value="<?php echo $acc; ?>">
</div>
<div class="input-group">
<label for="info">Info</label>
<textarea class="form-control" rows="8" name="info" id="info"><?php echo $row['info']; ?></textarea>
</div>
<div class="input-group">
<?php if ($update == true): ?>
<button class="btn" type="submit" name="update" style="background: #556B2F;" >update</button>
<?php else: ?>
<button class="btn" type="submit" name="save" >Add Account</button>
<?php endif ?>
</div>
</form>
</div><!-- left closed -->
<div class="right">
hello
</div> <!-- right closed -->
</div> <!-- container closed -->
</body>
</html>
---php_code.php-----
<?php
session_start();
$db = mysqli_connect('localhost', 'root', '', 'jskrecords');
// initialize variables
$name = "";
$acc = "";
$info = "";
$id = 0;
$update = false;
if (isset($_POST['save'])) {
$name = $_POST['name'];
$acc = $_POST['acc'];
$info = $_POST['info'];
mysqli_query($db, "INSERT INTO records (name, acc_no, info) VALUES ('$name', '$acc', '$info')");
$_SESSION['message'] = "Account saved";
header('location: index.php');
}
if (isset($_POST['update'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$acc = $_POST['acc'];
$info = $_POST['info'];
mysqli_query($db, "UPDATE records SET name='$name',acc_no='$acc',info='$info' WHERE id=$id");
$_SESSION['message'] = "Account updated!";
header('location: index.php');
}
if (isset($_GET['del'])) {
$id = $_GET['del'];
mysqli_query($db, "DELETE FROM records WHERE id=$id");
$_SESSION['message'] = "ACC deleted!";
header('location: index.php');
}
?>
Concept:
If you are creating multiple form from same mysql table using php script, You need to give each form a unique id.
e.g.
<form method="post" action="php_code.php" id="form<?= $id ?>">
Then add data-target="#form" to button with class 'inf'. It will store id of form.
<button class="inf" data-target="#form<?= $id ?>">show</button>
When button is clicked we know which form to open from data-target.
<script>
$('.container').on('click','button.inf',function(e){
e.preventDefault();
var formid=$(this).attr('data-target'); //get value of data-target attribute
//...proceed to play toggle with this form 'formid'
I'm working using ajax,javascript, php and still new with this.
Here the scenario, I have a button with onclick function in my index.html page when I click that button I want it to redirect me to another my getdata.php page while posting and id. So when I've been redirected to my getdata.php page I just need to query using that id.
The button that trigger redirection are located at index.html <button class="btn btn-default print" name="print" data-username="{{"'.$row['msid'].'"}}" onclick="generatepdf()"><span class="icon-printer"></button>
The following codes I've been using right now. I hope I've got a lot of help right here.
index.html
<?php
session_start();
$conn = mysqli_connect("localhost","root","1234","a0");
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Cache-control" content="no-cache"> <!--The No-Cache-->
<!--Bootstrap 3.3.7 CSS-->
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!--Data Tables-->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.13/css/dataTables.bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.1.1/css/responsive.bootstrap.min.css">
<!--Date Timepicker-->
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!--Linear Icons-->
<link rel="stylesheet" href="https://cdn.linearicons.com/free/1.0.0/icon-font.min.css">
<!--Date Timepicker-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/js/bootstrap-datetimepicker.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/css/bootstrap-datetimepicker.min.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.min.css">
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">MENU</button>
<a class="navbar-brand" href="#"><span class="icon-bag"></span> SUPPLIER</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<div class="container-fluid">
<h2 >List of Machine</h2>
<div class="table-responsive">
<div align="right">
<button type="button" id="add_button" data-toggle="modal" data-target="#userModal" class="btn btn-success">New File <span class="fa fa-code-fork"></span></button>
</div>
<br>
<table id="user_data" class="table table table-bordered table-hover dt-responsive " width="100%">
<thead>
<tr>
<th width="5%">Image</th>
<th width="15%">Name</th>
<th width="10%">Date Added</th>
<th width="10%">Created By</th>
<th width="6%">Action</th>
</tr>
</thead>
</table>
</div>
</div>
</body>
</html>
<div id="userModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="user_form" enctype="multipart/form-data">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add New Business Type </h4>
</div>
<div class="modal-body">
<label>Business Name</label>
<input type="text" name="businessname" id="businessname" class="form-control" />
<br />
<label>Select Business Image</label>
<input type="file" name="businessimage" id="businessimage" />
<span id="user_uploaded_image"></span>
</div>
<div class="modal-footer">
<input type="hidden" name="user_id" id="user_id" />
<input type="hidden" name="operation" id="operation" />
<input type="submit" name="action" id="action" class="btn btn-success" value="Add" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
var dataTable = $('#user_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"fetch.php",
type:"POST"
},
});
$(document).on('click', '.update', function(){
var user_id = $(this).attr("id");
$.ajax({
url:"fetch_single.php",
method:"POST",
data:{user_id:user_id},
dataType:"json",
success:function(data)
{
$('#userModal').modal('show');
$('#businessname').val(data.businessname);
$('.modal-title').text("Update Business Type");
$('#user_id').val(user_id);
$('#user_uploaded_image').html(data.businessimage);
$('#action').val("Save Changes");
$('#operation').val("Edit");
}
})
});
$(document).on('click', '.delete', function(){
var user_id = $(this).attr("id");
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
url:"delete.php",
method:"POST",
data:{user_id:user_id},
success:function(data)
{
alert(data);
dataTable.ajax.reload();
}
});
}
else
{
return false;
}
});
function generatepdf() {
var name = $(this).data('msid');
if (name != undefined && name != null) {
window.location = 'reports/getdata.php';
$.ajax({
url:"reports/getdata.php",
method:"POST"
});
}
};
});
</script>
<!--Data Table JS-->
<script type="text/javascript" src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.13/js/dataTables.bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.1.1/js/dataTables.responsive.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.1.1/js/responsive.bootstrap.min.js"></script>
</body>
fetch.php
<?php
include('db.php');
include('function.php');
$query = '';
$output = array();
$query .= "SELECT * FROM machine_supplier ";
if(isset($_POST["search"]["value"]))
{
$query .= 'WHERE machine_description LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY msid DESC ';
}
if($_POST["length"] != -1)
{
$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connection->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
$image = '';
if($row["image1"] != '')
{
$image = '<img src="machine_images/'.$row["image1"].'" class="img-thumbnail" width="50" height="35" />';
}
else
{
$image = '';
}
$sub_array = array();
$sub_array[] = $image;
$sub_array[] = $row["machine_description"];
$sub_array[] = $row["model_number"];
$sub_array[] = $row["supplier"];
$sub_array[] = '<select class="form-control">
<option selected disabled>YOUR ACTIONS</option>
<option name="update" id="'.$row["msid"].'" class="update">UPDATE</option>
<option name="delete" id="'.$row["msid"].'" class="delete">DELETE</option>
</select>
<button class="btn btn-default print" name="print" data-username="{{"'.$row['msid'].'"}}" onclick="generatepdf()"><span class="icon-printer"></button>
';
$data[] = $sub_array;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $filtered_rows,
"recordsFiltered" => get_total_all_records(),
"data" => $data
);
echo json_encode($output);
?>
function.php
<?php
function upload_image()
{
if(isset($_FILES["image1"]))
{
$extension = explode('.', $_FILES['image1']['name']);
$new_name = rand() . '.' . $extension[1];
$destination = 'machine_images/' . $new_name;
move_uploaded_file($_FILES['image1']['tmp_name'], $destination);
return $new_name;
}
}
function get_image_name($user_id)
{
include('db.php');
$statement = $connection->prepare("SELECT image1 FROM machine_supplier WHERE msid = '$user_id'");
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
return $row["image1"];
}
}
function get_total_all_records()
{
include('db.php');
$statement = $connection->prepare("SELECT * FROM machine_supplier");
$statement->execute();
$result = $statement->fetchAll();
return $statement->rowCount();
}
?>
getdata.php
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "databasename";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['print'])) {
$sql = "SELECT msid FROM machine_supplier WHERE";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//data
}
} else {
echo "0 results";
}
} else{
//redirect back
}
?>
</body>
</html>
Easy way is not using JS or Jquery for your requirement. Just use HTML form and PHP only like following in your index.php.
<?php
//In you index.php
//.....................
//..........................
//your other codes
//......................
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<form method="post" action="getdata.php">
<input type="hidden" name="my_id" value="<?php echo $row['msid']; ?>" />
<input type="submit" value="REDIRECT AND POST MY ID" />
</form>
<?php
}
} else {
echo "0 results";
}
//.................
//.................
You just need to replace the button code with this form code and your ID will be posted and redirected to getdata.php page because of the form attribute action="getdata.php".
See the form method is post this means your form will be submitted using POST method. Now in your getdata.php file do following
<?php
$posted_id = $_POST['my_id'];
echo $posted_id;
//now get data from DB using this id
//get data from db where id = $posted_id
This is not full code for getdata.php but you will see at least your posted id(from index.php to getdata.php) using this code. There are lots to do like checking http method, error handling etc etc.
im having problem with the integration of text fields with php by $_post method and i've done almost complete code but it giving me boolean error in line 84 which is
if(mysqli_num_rows ||($run)==0)
and my whole code is
<!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>
<h1 align="center">Registration form</h1>
<form action="registration.php" method="post">
<table align="center" border="2">
<tr>
<td>User name</td> <td><input type="text" placeholder="username" name="name" /></td>
</tr>
<tr>
<td>Password</td> <td><input type="password" placeholder="password" name="password" /></td>
</tr>
<tr>
<td>Email</td> <td><input type="email" placeholder="email" name="email" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="submit" name="submit" /></td>
</tr>
</table>
</form>
</body>
</html>
<?php
//connection to database
$servername = "localhost";
$db_username = "user_db_users";
$db_password = "123456789";
$db_name = "users_db";
$conn = new mysqli($servername, $db_username, $db_password, $db_name);
//fatching data from form
if(isset($_POST['submit'])){
$user_name = $_POST['name'];
$user_pass = $_POST['password'];
$user_email = $_POST['email'];
//validatio form
if($user_name==''){
echo "<script>alert('please enter usernmae')</script>";
exit();
}
if($user_pass==''){
echo "<script>alert('please enter password')</script>";
exit();
}
if($user_email==''){
echo "<script>alert('please enter email')</script>";
exit();
}
$check_email = "select * from users where user_email='$user_email'";
$run = mysql_query($check_email);
if(mysqli_num_rows ||($run)==0){
echo "<script>alert('Email $check_email is already exist')</script>";
exit();
}
//Getting values from fields of registration form
$query = "insert into users(user_name, user_pass, user_email) values($user_name, $user_pass, $user_email)";
if(mysql_query($query)){
echo "<script>alert('registration successful')</script>";
}
}
?>
The function mysqli_num_rows() need a mysqli_result parameter and if you want the logic to work correctly the test is actually wrong as well
So change
if(mysqli_num_rows ||($run)==0){
To
if(mysqli_num_rows($run) > 0) {
This query will also fail
$query = "insert into users(user_name, user_pass, user_email)
values($user_name, $user_pass, $user_email)";
All text column variables should be wrapped in quotes like this
$query = "insert into users(user_name, user_pass, user_email)
values('$user_name', '$user_pass', '$user_email')";
But I have to mention that Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
Use prepared parameterized statements
I am very new to php just today itself I have started learning it, I am doing a simple program from of selecting a row from mysql's database based on user input on html through php file . and my concern is when I submit the form , it redirects to to the php and the output is displayed on the php, how can I display the result on the HTML page itself I mean the user shouldn't feel there is any transition from html to php any we get the output on the html page
HTML page :
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form action="index.php" method="get">
Enter Name : <input type="text" id="txt1" name="user">
<input type="submit" name="enter">
</form>
</body>
php page :
<?php
$dbhost = "localhost";
$username = "root";
$password = "";
mysql_connect($dbhost,$username,$password);
#mysql_select_db("trynew") or die(mysql_error());
if (isset($_GET["user"])) {
$user = $_GET['user'];
}
$query = "SELECT * FROM trynewtable where name = '$user' ";
$result = mysql_query($query);
if($result==FALSE)
{
die(mysql_error());
}
$row = mysql_fetch_array($result);
echo $row[0];
echo $row[1];
echo $row[2];
echo $row[3];
mysql_close();
?>
On the user side theres no difference between html and php, php files are also html in the view of the browser. The only difference is that php files are interpreted by the server ,while html is just send. So you can put your html in your php and mix it all together:
index.php:
<body>
<div id="response">
<?php
if($_SERVER["REQUEST_METHOD"]=="POST"){
//do your request
}else{
echo "please fill in the form";
}
?>
</div>
//your form etc
Simple answer You can merge the HTML and PHP files unless there is a need to separate them (if so use AJAX). Do a validation before any database interaction. Do not use mysql but mysqli_
<?php
$dbhost = "localhost";
$username = "root";
$password = "";
$col1 = $col2=$col3=$col4="";
mysql_connect($dbhost,$username,$password);
#mysql_select_db("trynew") or die(mysql_error());
if (isset($_GET["user"])) {
$user = $_GET['user'];
$query = "SELECT * FROM trynewtable where name = '".mysql_real_escape_string($user)."' ";
$result = mysql_query($query);
if($result==FALSE) {
die(mysql_error());
}
$row = mysql_fetch_array($result);
$col1 = $row[0];
$col2 = $row[1];
$col3 = $row[2];
$col4 = $row[3];
}
mysql_close();
?>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php echo $col1." ".$col2." ".$col3." ".$col4;?>
<form action="" method="get">
Enter Name : <input type="text" id="txt1" name="user">
<input type="submit" name="enter">
</form>
</body>