PHP and MySQL insert into multiple tables from one form - php

I am creating a simple site to keep records of users, customers, suppliers, etc.
I have created the forms to register clients and users using single forms capturing data through $ _POST form method
So far I have not had problems since the INSERTS are done on singles table which PK is an AutoIncremented field
In the code shown below, my goal is to let users create a vendor (name, phone number, email, address) as well as assign 1 or many vendor-category. This information is contained in one form
vendors, vendors-categories, users, etc. are stored in a MySQL database with the structure shown:
There is something wrong about my code after successfully create vendor and I am not sure how to solve the part that manages insertions in the join table (tblprovxrubro)
Code
<?php
session_start();
//available for admin, power-users and role-4
if ($_SESSION['rol'] ==2) {
header("location: ./");
}
include "../conexion.php";
if (!empty($_POST)) {
$alert='';
if (empty($_POST['razonSocial'])|| empty($_POST['email'])) {
$alert='<p class="msg_error">Vendor name and email must not be blank.</p>';
}else{
$razonSocial = $_POST['razonSocial'];
$email = $_POST['email'];
$domicilio = $_POST['domicilio'];
$telefono = $_POST['telefono'];
$usuario_id = $_SESSION['iduser'];
$query = mysqli_query($conection,"SELECT * FROM tblprov WHERE razonSocial = '$razonSocial'");
$result = mysqli_fetch_array($query);
if ($result >0)
{
$alert='<p class="msg_error">vendor already exists.</p>';
}else{
$query_insert = mysqli_query($conection, "INSERT INTO tblprov(razonSocial, numero, domicilio, email, idUsuario)
VALUES('$razonSocial','$telefono','$domicilio','$email', '$usuario_id')");
if ($query_insert)
{
$alert='<p class="msg_save">Vendor created succesfully.</p>';
//Once vendor is created I need his ID in order to insert in table
//tblprovxrubro as many records as vendor-types selected in form
//Not sure about how to achieve this
$queryBuscaprov = mysqli_query($conection, "SELECT id FROM tblprov WHERE razonSocial = '$razonSocial'");
$result_prov = mysqli_fetch_array($queryBuscaProv);
$idProv = $result_prov['id'];
foreach ($_POST['idRubro'] as $opcionSeleccionada)
{
//This INSERT should execute as many times as vendor-types selected in form
$query2 = mysqli_query($conection, "INSERT INTO tblprovxrubro (idRubro, idProv) VALUES ('$opcionSeleccionada', '$idProv')");
}
}else{
$alert='<p class="msg_error">Error creating vendor.</p>';
}
}
}
mysqli_close($conection);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<?php include "includes/scripts.php"; ?>
<title>Registro de Proveedores</title>
</head>
<body>
<?php include "includes/header.php"; ?>
<section id="container">
<div class="form_register" name="form_register">
<h1><i class="fas fa-building"></i> Vendor List</h1>
<hr>
<form action="" method="post" class="form_register">
<div class="alert"><?php echo isset($alert) ? $alert : ''; ?></div>
<label for="razonSocial">Razón Social</label>
<input type="text" name="razonSocial" id="razonSocial" placeholder="Razón Social">
<label for="telefono">Número Telefónico</label>
<input type="text" name="telefono" id="telefono" placeholder="Número Telefónico">
<label for="domicilio">Domicilio</label>
<input type="text" name="domicilio" id="domicilio" placeholder="Domicilio">
<label for="email">Email</label>
<input type="text" name="email" id="email" placeholder="Email">
<?php
$query_rubro = mysqli_query($conection,"SELECT * FROM tblrubros");
mysqli_close($conection);
$result_rubro = mysqli_num_rows($query_rubro);
?>
<select name="rubro[]" id="rubro" multiple size="12">
<?php
if($result_rubro > 0)
{
while ($rubro = mysqli_fetch_array($query_rubro))
{
?>
<option value="<?php echo $rubro["idRubro"]; ?>"><?php echo $rubro["rubroDescripcion"] ?></option>
<?php
}
}
?>
</select>
<p>press Ctrl in order to select multiple options.</p>
<button name="submit" type="submit" class="btn_save"><i class="fas fa-save"></i> Crear Proveedor</button>
</form>
</div>
</section>
<?php include "includes/footer.php"; ?>
</body>
</html>
conection.php
<?php
$host = 'localhost';
$user = 'root';
$password = 'mypass';
$db = 'compras';
$conection = #mysqli_connect($host,$user,$password,$db);
mysqli_set_charset($conection,"utf8");
if(!$conection){
echo "connection error";
}
?>

Related

Togle to edit Mysql data from PHP

I have a table in my php where I show data from my 'users' table of mysql. In the table I added an edit button so that, if you click on the button, a form is shown below the table where you can edit some fields of the table's content, I have also added a delete button next to it to delete the row of the table you want, but that button works correctly.
The problem I have is with the edit button, which, when pressed, it doesn’t show me the form that I added below the table, but it takes me to the page 'registerTeacher.php?edit = 3' for example. Pressing the 'Edit' button, it should show the form to be able to edit but it doesn’t do anything, nor does it show me any errors. Can someone help me find where the problem is? Thank you.
This is my ‘indexAdmin.php’ code:
<?php
include('server.php');
include('Security.php');
include('Conexion.php');
include('registerTeacher.php');
?>
<?php
$style = "style='display:none;'";
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$update = true;
$record = mysqli_query($conn, "SELECT * FROM users WHERE id=$id");
if (#count($record) == 1 ) {
$n = mysqli_fetch_array($record);
$username = $n['username'];
$email = $n['email'];
$style = "style='display:block;'";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="styleIndexAdmin.css">
<meta charset="utf-8">
</head>
<body>
<!-- notification message -->
<?php if (isset($_SESSION['success'])) : ?>
<div class="error success" >
<h3>
<?php
echo $_SESSION['success'];
unset($_SESSION['success']);
?>
</h3>
</div>
<?php endif ?>
<!-- logged in user information -->
<?php if (isset($_SESSION['username'])) : ?>
<div class="navbar" id="navbar">
<a class="tablink" onclick="openPage('professorsRegistered', this, 'lightblue')" id="defaultOpen">Profesores</a>
</div>
<!----------- PROFESSROS REGISTERED TABLE ----------->
<div id="professorsRegistered" class="tabcontent"></br><br>
<table class="professorsRegistered">
<tr>
<th colspan="3"><h2>PROFESSORS REGISTERED</h2></th>
</tr>
<tr>
<th> Name </th>
<th> Edit </th>
<th> Delete </th>
</tr>
<?php
$result = $conn->query($sql);
$sql = "SELECT * FROM users WHERE rol='profesor'";
$result = $conn->query($sql);
if ($result->num_rows==0){
echo 'No professors';
}else{
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>".$row["username"]."</td>
<td><a href='registerTeacher.php?edit=".$row["id"]."' class='edit_btn' ><i class='fa fa-pencil-square-o' style='cursor:pointer;'></i></a></td>
<td><a class='eliminate' onClick=\"javascript: return confirm('Confirm to delete');\" href=\"deleteTeacher.php?id=".$row['id']."\">X</a></td>
</tr>";
}
}
?>
</table><br><br>
<!------- FORM TO EDIT REGISTERED TEACHERS ---------->
<form method="post" action="registerTeacher.php" <?php echo $style;?>>
<!----- newly added field--->
<input type="hidden" name="id" value="<?php echo $id; ?>">
<div class="input-group">
<label>USER</label>
<input type="text" name="username" value="<?php echo $username; ?>">
</div>
<div class="input-group">
<label>EMAIL</label>
<input type="email" name="email" value="<?php echo $email; ?>">
</div>
<div class="input-group">
<!--------BUTTON----->
<?php if ($update == true): ?>
<button class="btn_update" type="submit" name="update">EDIT</button>
<?php endif ?>
</div>
</form>
</div>
<?php endif ?>
<script>
function getUrlVars(){
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value){
vars[key] =value;
});
return vars;
}
function openPage(pageName,elmnt,color) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablink");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].style.backgroundColor = "";
}
document.getElementById(pageName).style.display = "block";
elmnt.style.backgroundColor = color;
}
p = getUrlVars()["page"];
//alert(p);
if (p==undefined){
document.getElementById("defaultOpen").click();
}else{
openPage(p, this, 'lightblue');
}
</script>
</body>
<?php if (isset($_SESSION['message'])): ?>
<div class="msg">
<?php
echo $_SESSION['message'];
unset($_SESSION['message']);
?>
</div>
<?php endif ?>
</html>
This is my ‘registerTeacher.php’ file:
<?php
include('Conexion.php');
$username = "";
$email = "";
$errors = array();
$id = 0;
$update = false;
// UPDATE
if (isset($_POST['update'])) {
$id = $_POST['id'];
$username = $_POST['username'];
$email = $_POST['email'];
mysqli_query($conn, "UPDATE users SET username='$username', email='$email' WHERE id=$id");
$_SESSION['message'] = "User edited!";
header("Location: indexAdmin.php?page=professors");
}
?>
Because <a href=..> is used to redirect to some page in your case ,it is redirecting to registerTeacher.phppage as you have specify in your href attribute.Instead you can do like below :
When below <a href..> is clicked you can put form on registerTeacher.php like below :
<?php
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$update = true;
$record = mysqli_query($conn, "SELECT * FROM users WHERE id=$id");
if (#count($record) == 1 ) {
$n = mysqli_fetch_array($record);
$username = $n['username'];
$email = $n['email'];
$style = "style='display:block;'";
}
}
?>
<!------- FORM TO EDIT REGISTERED TEACHERS ---------->
<form method="post" action="abcpage.php" <?php echo $style;?>>
<!----- newly added field--->
<input type="hidden" name="id" value="<?php echo $id; ?>">
<div class="input-group">
<label>USER</label>
<input type="text" name="username" value="<?php echo $username; ?>">
</div>
<div class="input-group">
<label>EMAIL</label>
<input type="email" name="email" value="<?php echo $email; ?>">
</div>
<div class="input-group">
<!--------BUTTON----->
<?php if ($update == true): ?>
<button class="btn_update" type="submit" name="update">EDIT</button>
<?php endif ?>
</div>
</form>
Then you can passed this details to your action="abcpage.php".and write like below in that page i.e :
// UPDATE
if (isset($_POST['update'])) {
$id = $_POST['id'];
$username = $_POST['username'];
$email = $_POST['email'];
mysqli_query($conn, "UPDATE users SET username='$username', email='$email' WHERE id=$id");
$_SESSION['message'] = "User edited!";
header("Location: indexAdmin.php?page=professors");
}
?>
Hope this helps !
Note : Also try using prepared statement it is safe an secure.

PHP Insert into MySQL Database doesn't work

I'm trying to input data into MySQL Database. I can log into database. However, whenever I run, the error "Error Querying Database 2" keeps appearing.
I'm suspecting my SQL Query having problems. However, I have checked my SQL query several times but I can't find any errors. (not yet)
Any help is appreciated!
<!DOCTYPE HTML>
<html>
<head>
<title>Create Events</title>
<link rel="stylesheet" href="RegisterLogin.css">
</head>
<?php
session_start();
if (isset($_SESSION['Username'])) {
$Username=$_SESSION['Username'];
}
?>
<body>
<?php
//define variables and set to empty values
$EventNameErr = $MembersAttending_Err = $EventDateErr = $LocationErr = $websiteErr = "";
$EventName = $MembersAttending = $EventDate = $Location = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["EventName"])) {
$EventNameErr = "A name for the event is required";
} else {
$EventName = test_input($_POST["EventName"]);
}
if (empty($_POST["MembersAttending"])) {
$MembersAttendingErr = "How many members are attending";
} else {
$MembersAttending = test_input($_POST["MembersAttending"]);
}
if (empty($_POST["EventDate"])) {
$EventDateErr = "The date of the event is required";
} else {
$EventDate = test_input($_POST["EventDate"]);
}
if (empty($_POST["Location"])) {
$LocationErr = "Location of the event is required";
} else {
$Location = test_input($_POST["Location"]);
}
//continues to target page if all validation is passed
if ( $EventNameErr ==""&& $MembersAttendingErr ==""&& $EventDateErr ==""&& $LocationErr == ""){
// check if exists in database
$dbc=mysqli_connect('localhost','testuser','password','Project')
or die("Could not Connect!\n");
$sql="SELECT * from Events WHERE EventName ='$EventName';";
$result =mysqli_Query($dbc,$sql) or die (" Error querying database 1");
$a=mysqli_num_rows($result);
if ($a>0){
$EventNameErr="Event Name already exists".$a;
} else {
$sql1="INSERT INTO Events VALUES(NULL,'$EventName','$MembersAttending','$EventDate','$Location');";
$result =mysqli_Query($dbc,$sql1) or die (" Error querying database 2");
mysqli_close();
header('Location: /EventCreated.php');
}
}
}
// clears spaces etc to prep data for testing
function test_input($data){
$data=trim ($data); // gets rid of extra spaces befor and after
$data=stripslashes($data); //gets rid of any slashes
$data=htmlspecialchars($data); //converts any symbols usch as < and > to special characters
return $data;
}
?>
<h2 style="color:yellow" align="center"> Event Creation </h2>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" align="center" style="color:#40ff00">
EventName:
<input type="text" name="EventName" value="<?php echo $EventName;?>"/>
<span class="error">* <?php echo $EventNameErr;?></span>
<br/><br/>
Members:
<input type="text" name="MembersAttending" value="<?php echo $MembersAttending;?>"/>
<span class="error">* <?php echo $MembersAttendingErr;?></span>
<br/><br/>
Date:
<input type="text" name="EventDate" value="<?php echo $EventDate;?>"/>
<span class="error">* <?php echo $EventDateErr;?></span>
<br/><br/>
Location:
<input type="text" name="Location" value="<?php echo $Location;?>"/>
<span class="error">* <?php echo $LocationErr;?></span>
<br/><br/>
<input type="Reset" name="Reset" value="Reset">
<input type="submit" name="submit" value="Submit"/> 
</form>
</body>
</html>
I'm not sure what are the column name available in your table, but try with the following query,
I got the column name form your code, I'm not sure it's right or wrong. just try it.
$sql1="INSERT INTO Events (EventName,MembersAttending,EventDate,Location)
VALUES('$EventName','$MembersAttending','$EventDate','$Location');";

php echo listbox value from databasebase

I have 2 tables
TABLE joke (id, joke_text, joke_date, author_id)
TABLE author(id, name, email)
I am having a problem in echoing the value inserted within author_id field in the list box:
<?php
# display all php errors
error_reporting(-1);
ini_set('display_errors', 1);
# include dbConnection details
require '../includes/dbconn.php';
# initially set $id to empty
$id = null;
# if $id is not empty, GET the id
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
# if $id is empty then send the user back to index.php
if ( null==$id ) {
header("Location: index.php");
exit();
}
if ( !empty($_POST)) {
// keep track validation errors
$joke_textError = null;
$authorError = null;
// keep track post values
$joke_text = $_POST['joke_text'];
$author_id = $_POST['author_id'];
// validate input
$valid = true;
if (empty($joke_text)) {
$joke_textError = 'Please enter joke text';
$valid = false;
}
// update data
if ($valid) {
$sql = "UPDATE joke set joke_text = ?, author_id = ? WHERE id = ?";
$update = $dbConnection->prepare($sql);
$update->execute(array($joke_text,$author_id,$id));
header("Location: index.php");
exit();
}
} else {
$sql = "SELECT joke.id, joke.joke_text, joke.joke_date, author.name, author.email, joke.author_id, author.id
FROM joke INNER JOIN author
ON author_id = author.id
WHERE joke.id = ?";
$select = $dbConnection->prepare($sql);
$select->execute(array($id));
$data = $select->fetch();
$joke_id = $data['id'];
$joke_text = $data['joke_text'];
$joke_date = $data['joke_date'];
$author_name = $data['name'];
$author_email = $data['email'];
$author_id = $data['author_id'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Update Author</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="../includes/styles.css" />
</head>
<body>
<div class="container">
<div class="row">
<h1>Update Author</h1>
</div>
<form action="update.php?id=<?php echo $id?>" method="post">
<div class="control-group <?php if (!empty($nameError)){ echo 'error';}?>">
<label class="control-label">Name</label>
<div class="controls">
<input name="joke_text" type="text" placeholder="joke text" value="<?php if (!empty($joke_text)){ echo htmlspecialchars(trim($joke_text)); } ?>">
<?php if (!empty($joke_textError)) {
echo '<span class="help-inline">' . $joke_textError . '</span>';
} ?>
</div>
</div>
<select name="author_id" id="author_id">
<option value="">Select one</option>
<?php
$sql2 = 'SELECT id, name FROM author';
foreach ($dbConnection->query($sql2) as $data2) { ?>
<option value="<?php echo $data2['id']; ?>"
<?php if(isset($_POST['author_id']) && $_POST['author_id'] == $data['author_id']) { echo 'selected'; } ?>>
<?php echo htmlspecialchars($data2['name'], ENT_QUOTES, 'UTF-8'); ?>
</option>
<?php } ?>
</select>
<div class="form-actions">
<button type="submit" class="btn btn-green">Update</button>
<a class="btn" href="index.php">Back</a>
</div>
</form>
</div>
</div>
</body>
</html>
The data updates into the database just fine, can not figure how to echo it back out into the author_id listbox. If someone could kindly give some assistance it would be great!

Adding new record and updating record failing in mySQL table with jQuery

I'm following this article on how to do CRUD operations with jQuery dynamically and trying to integrate it with my PHP/MySQL application. However, the add and update record functions are not working and I'm unsure of where it is failing. My knowledge of AJAX and jQuery are limited.
Edit: Add and Update didn't work because I didn't have an ID attached to the carrier selects. Once I added the proper ID, everything started working again. Will update my staff.php to show what it should look like for anyone curious.
The MySQL table used for this is generated on the fly based, but the tables have the following rows:
id
email
mobilePhone
mobileCarrier
firstName
lastName
My code:
Staff.php
<?php
session_start();
require_once('../connection.php');
//get session variable, if empty, unset and logout
if(empty($_SESSION['department'])) {
session_unset();
session_destroy();
header("Location: index.php");
} else {
$dept = $_SESSION[department];
}
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Visitor Management</title>
<link rel="stylesheet" href="../css/foundation.min.css" />
<link rel="stylesheet" href="../css/app.css" />
<link type="text/css" rel="stylesheet" href="https://fast.fonts.net/cssapi/24365087-b739-4314-af6e-741946b60bef.css"/>
<link type="text/css" rel="stylesheet" href="https://fast.fonts.net/cssapi/b05259d9-ca62-44a8-8a19-d3facdbd64df.css"/>
<link type="text/css" rel="stylesheet" href="https://fast.fonts.net/cssapi/2603d516-f938-4b52-ae3a-11d25bb4c555.css"/>
<link type="text/css" rel="stylesheet" href="https://fast.fonts.net/cssapi/510266cf-74ab-4fa8-9b39-dd37b90d6ab0.css"/>
</head>
<body>
<?php
if (!$_SESSION['user']) {
header("Location: ../login.php"); // If session is not set that redirect to Login Page
}
?>
<!-- nav -->
<div class="top-bar admin">
<div class="top-bar-left">
<ul class="menu">
<li class="menu-text">Visitor Management</li>
</ul>
</div>
<div class="top-bar-right">
<ul class="menu">
<li>Logout</li>
</ul>
</div>
</div>
<div class="medium-2 columns dash">
<ul>
<li>Dashboard</li>
<li class="active">Staff</li>
<li>Reports</li>
</ul>
</div>
<div class="medium-10 columns">
<div class="row checkin">
<h2>Staff Profiles</h2>
<h3>All Staff</h3>
<button class="button success" data-open="addStaff">Add New Staff Member</button>
<div class="staff"></div>
<!-- Add Staff Modal -->
<div class="reveal" id="addStaff" data-reveal>
<h3>Add New Staff Member</h3>
<label>First Name
<input type="text" placeholder="" id="firstname">
</label>
<label>Last Name
<input type="text" placeholder="" id="lastname">
</label>
<label>Email Address
<input type="email" placeholder="" id="email">
</label>
<label>Mobile Phone Number
<input type="tel" placeholder="" id="phone">
</label>
<label>Mobile Phone Carrier
<select name="carrier" id="carrier">
<option value="None"> </option>
<option value="AT&T">AT&T</option>
<option value="Verizon">Verizon</option>
<option value="Sprint">Sprint</option>
<option value="TMobile">T-Mobile</option>
<option value="Metro PCS">Metro PCS</option>
</select>
</label>
<button class="button" type="button" onclick="addRecord()">Submit</button>
<button class="close-button" data-close aria-label="Close modal" type="button">
<span aria-hidden="true">×</span>
</button>
</div>
<!-- Edit Staff Modal -->
<div class="reveal" id="editStaff" data-reveal>
<h3>Edit Staff Member</h3>
<label>First Name
<input type="text" placeholder="" id="update_firstname">
</label>
<label>Last Name
<input type="text" placeholder="" id="update_lastname">
</label>
<label>Email Address
<input type="email" placeholder="" id="update_email">
</label>
<label>Mobile Phone Number
<input type="tel" placeholder="" id="update_phone">
</label>
<label>Mobile Phone Carrier
<select name="update_carrier" id="update_carrier">
<option value="None"> </option>
<option value="AT&T">AT&T</option>
<option value="Verizon">Verizon</option>
<option value="Sprint">Sprint</option>
<option value="TMobile">T-Mobile</option>
<option value="Metro PCS">Metro PCS</option>
</select>
</label>
<button class="button" type="button" onclick="UpdateUserDetails()">Submit</button>
<button class="close-button" data-close aria-label="Close modal" type="button">
<span aria-hidden="true">×</span>
</button>
<input type="hidden" id="hidden_user_id">
</div>
</div>
</div>
<script src="../js/vendor/jquery.min.js"></script>
<script src="../js/vendor/what-input.min.js"></script>
<script src="../js/foundation.min.js"></script>
<script src="../js/app.js"></script>
<script>
// Add Staff Member
function addRecord() {
// get values
var firstname = $("#firstname").val();
var lastname = $("#lastname").val();
var email = $("#email").val();
var phone = $("#phone").val();
var carrier = $("#carrier").val();
// Add record
$.post("addRecord.php", {
firstname: firstname,
lastname: lastname,
email: email,
phone: phone,
carrier: carrier
}, function (data, status) {
// close the popup
$("#addStaff").foundation("close");
// read records again
readRecords();
// clear fields from the popup
$("#firstname").val("");
$("#lastname").val("");
$("#email").val("");
$("#phone").val("");
$("#carrier").val("");
});
}
// READ staff members
function readRecords() {
$.get("readRecords.php", {}, function (data, status) {
$(".staff").html(data);
});
}
$(document).ready(function () {
// READ recods on page load
readRecords(); // calling function
});
// Delete staff member
function DeleteUser(id) {
var conf = confirm("Are you sure, do you really want to delete this staff member?");
if (conf == true) {
$.post("deleteUser.php", {
id: id
},
function (data, status) {
// reload Users by using readRecords();
readRecords();
}
);
}
}
// Get staff member details
function GetUserDetails(id) {
// Add User ID to the hidden field for furture usage
$("#hidden_user_id").val(id);
$.post("readUserDetails.php", {
id: id
},
function (data, status) {
// PARSE json data
var user = JSON.parse(data);
// Assing existing values to the modal popup fields
$("#update_firstname").val(user.firstName);
$("#update_lastname").val(user.lastName);
$("#update_email").val(user.email);
$("#update_phone").val(user.mobilePhone);
$("#update_carrier").val(user.mobileCarrier);
}
);
// Open modal popup
$("#editStaff").foundation("open");
}
function UpdateUserDetails() {
// get values
var firstname = $("#update_firstname").val();
var lastname = $("#update_lastname").val();
var email = $("#update_email").val();
var phone = $("#update_phone").val();
var carrier = $("#update_carrier").val();
// get hidden field value
var id = $("#hidden_user_id").val();
// Update the details by requesting to the server using ajax
$.post("updateUserDetails.php", {
id: id,
firstname: firstname,
lastname: lastname,
email: email,
phone: phone,
carrier: carrier
},
function (data, status) {
// hide modal popup
$("#editStaff").foundation("close");
// reload Users by using readRecords();
readRecords();
}
);
}
</script>
</body>
</html>
Connection.php
<?php
# FileName="connection.htm"
# Type="MYSQL"
# HTTP="true"
$hostname_VisitorManagement = "localhost";
$database_VisitorManagement = "visitor-management";
$username_VisitorManagement = "***";
$password_VisitorManagement = "***";
$VisitorManagement = mysqli_connect($hostname_VisitorManagement, $username_VisitorManagement, $password_VisitorManagement, $database_VisitorManagement);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
date_default_timezone_set('America/New_York');
?>
addRecord.php
<?php
// include Database connection file
session_start();
require_once('../connection.php');
if(empty($_SESSION['department'])) {
session_unset();
session_destroy();
header("Location: ../index.php");
} else {
$dept = $_SESSION[department];
}
$staffTable = $dept . "_staff";
if(isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['email']) && isset($_POST['phone']) && isset($_POST['carrier']))
{
// get values
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$carrier = $_POST['carrier'];
$query = "INSERT INTO {$staffTable}(firstName, lastName, email, mobilePhone, mobileCarrier) VALUES('$firstname', '$lastname', '$email', '$phone', '$carrier')";
if (!$result = mysqli_query($VisitorManagement, $query)) {
exit(mysqli_error($VisitorManagement));
}
echo "Staff Member Has Been Added!";
}
?>
readRecords.php
<?php
// include Database connection file
session_start();
require_once('../connection.php');
if(empty($_SESSION['department'])) {
session_unset();
session_destroy();
header("Location: ../index.php");
} else {
$dept = $_SESSION[department];
}
$staffTable = $dept . "_staff";
// Design initial table header
$data = "<table id='staff'>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Mobile Phone</th>
<th>Mobile Carrier</th>
<th></th>
</tr>
</thead>";
$query = "SELECT * FROM {$staffTable} ORDER BY lastName";
if (!$result = mysqli_query($VisitorManagement, $query)) {
exit(mysqli_error($VisitorManagement));
}
// if query results contains rows then featch those rows
if(mysqli_num_rows($result) > 0)
{
$number = 1;
while($row = mysqli_fetch_assoc($result))
{
$data .= '<tbody>
<tr>
<td>'.$row['firstName'] . " " . $row['lastName'].'</td>
<td>'.$row['email'].'</td>
<td>'.$row['mobilePhone'].'</td>
<td>'.$row['mobileCarrier'].'</td>
<td>
<button onclick="GetUserDetails('.$row['id'].')" class="button secondary">Edit</button> <button onclick="DeleteUser('.$row['id'].')" class="button alert">Delete</button>
</td>
</tr>
</tbody>';
$number++;
}
}
else
{
// records now found
$data .= '<tr><td colspan="6">Records not found!</td></tr>';
}
$data .= '</table>';
echo $data;
?>
deleteUser.php
<?php
// include Database connection file
session_start();
require_once('../connection.php');
if(empty($_SESSION['department'])) {
session_unset();
session_destroy();
header("Location: ../index.php");
} else {
$dept = $_SESSION[department];
}
$staffTable = $dept . "_staff";
// check request
if(isset($_POST['id']) && isset($_POST['id']) != "")
{
// get user id
$user_id = $_POST['id'];
// delete User
$query = "DELETE FROM {$staffTable} WHERE id = '$user_id'";
if (!$result = mysqli_query($VisitorManagement, $query)) {
exit(mysqli_error($VisitorManagement));
}
}
?>
readUserDetails.php
<?php
// include Database connection file
session_start();
require_once('../connection.php');
if(empty($_SESSION['department'])) {
session_unset();
session_destroy();
header("Location: ../index.php");
} else {
$dept = $_SESSION[department];
}
$staffTable = $dept . "_staff";
// check request
if(isset($_POST['id']) && isset($_POST['id']) != "")
{
// get User ID
$user_id = $_POST['id'];
// Get User Details
$query = "SELECT * FROM {$staffTable} WHERE id = '$user_id'";
if (!$result = mysqli_query($VisitorManagement, $query)) {
exit(mysqli_error($VisitorManagement));
}
$response = array();
if(mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$response = $row;
}
}
else
{
$response['status'] = 200;
$response['message'] = "Data not found!";
}
// display JSON data
echo json_encode($response);
}
else
{
$response['status'] = 200;
$response['message'] = "Invalid Request!";
}
?>
updateUserDetails.php
<?php
// include Database connection file
session_start();
require_once('../connection.php');
if(empty($_SESSION['department'])) {
session_unset();
session_destroy();
header("Location: ../index.php");
} else {
$dept = $_SESSION[department];
}
$staffTable = $dept . "_staff";
// check request
if(isset($_POST))
{
// get values
$id = $_POST['id'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$carrier = $_POST['carrier'];
// Updaste User details
$query = "UPDATE {$staffTable} SET firstName = '$firstname', lastName = '$lastname', email = '$email', mobilePhone = '$phone', mobileCarrier = '$carrier' WHERE id = '$id'";
if (!$result = mysqli_query($VisitorManagement, $query)) {
exit(mysqli_error($VisitorManagement));
}
}
?>
Am I missing something? Has anyone used that article before to create add, update, and delete records functions before?
Thank you for your help.
The best you can do now is to debug your code (using developers function of your browser - check if your ajax script is called properly) and/or check your php error log.
anyway, remove curly brackets in the insert/update query, it may helps too

Update a query by substracting a multiplicated number and using where

I'm making a paid to click website and I'm looking to update a query by substracting and a multiplicated number.
I'm trying to get the users to buy some ads package, they enter the views count and the cost per view, then when they click on "Submit", it should update the user in the current session. However, it's not working: it's updating all the users balances.
Here's my code :
<?php
session_start();
require_once '../constants/initSite.php';
$siteConstant->addFile('css', 'account.css');
echo $siteConstant->getHead();
echo $siteConstant->getMenu();
if(isset($_SESSION['username']) && isset($_SESSION['password'])){
require_once '../constants/class.DatabaseConstants.php';
require_once '../class/class.DBase.php';
$done = false;
$db = new DatabaseConstants();
$dBase = new DBase($db->getHost(), $db->getUser(), $db->getPass());
$dBase->setDatabaseName($db->getDb());
if(!$dBase->connectDatabase()){
die('SQL ERROR at db class vd fn');
}
$userQuery = mysqli_query($dBase->getDbobj(), "SELECT * FROM members WHERE username=\"".$_SESSION['username']."\"");
if(mysqli_num_rows($userQuery)){
$userData = mysqli_fetch_assoc($userQuery);
}else{
die('User Not Found!');
}
if(isset($_POST['submit'])){
$adquery = 'INSERT INTO ads (Title,Link,ViewLimit,Pays) VALUES ("'.$_POST['title'].'","'.$_POST['link'].'","'.$_POST['views'].'","'.$_POST['pays'].'")';
mysqli_query($dBase->getDbobj(), $adquery);
if(!mysqli_affected_rows($dBase->getDbobj())<1){
$done = true;
}
$id = 0;
$qryE = mysqli_query($dBase->getDbobj(), 'SELECT Id FROM ads');
while($dataE = mysqli_fetch_assoc($qryE)){
$id = $dataE['Id'];
}
$userQueryE = mysqli_query($dBase->getDbobj(),'SELECT id FROM members');
while($userDataE = mysqli_fetch_assoc($userQueryE)){
mysqli_query($dBase->getDbobj(), 'INSERT INTO view (MemberId,AdId) VALUES ("'.$userDataE['id'].'","'.$id.'")');
}
$userquery = ('UPDATE members SET balance=("'.$userData['balance'].'" - "'.$_POST['views'].'" * "'.$_POST['pays'].'") WHERE username="'.$_SESSION['username'].'"') ;
$userData = mysqli_fetch_assoc($userQuery);
}
?>
<center><img style="margin-bottom:5px"src="../image/ad468x60.png"/></center>
<div id="maincontent" style="height:35em">
<center>
<ul id="menu2">
<li>Account Details</li>
<li>Add Advertisement</li>
<li>Request Payment</li>
<li>Referrals</li>
<li>Account Setting</li>
</ul>
<br>
</center>
<center><p style="color:#0481b1;"><b><u>Add Advertisements</u></b></p></center>
<form id="msform" method="POST" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
<center>
<?php
if(isset($_POST['submit']) && !$done){
echo '<h3 style="color:red;">Something went wrong!</h3>';
}
if ($done){
echo '<h3 style="color:green;">Advertisement Added and is Active.</h3>';
}
?>
<?php
if($userData['balance'] < 5 ){
echo '<h3 style="color:red;">insufficient balance</h3></br>
<h2 style="color:red;text-decoration:underline">You currently have '.$userData['balance'].' '.$siteData['currency'].' </h2>
<center><h2 style="color:red">You do not have enough balance to add an advertissement.<br><br>You need to have at least 5 '.$siteData['currency'].' in your account balance to add an advertissement.</h2></center>';
}
else {
echo'
Title <input type="text" name="title" placeholder="Enter Site Title" required="true"/> <br><br>
Link <input type="text" name="link" placeholder="Enter Site Link" required="true"/><br><br>
Number of Viewers to send<input type="text" name="views" min="100" placeholder="Enter number of views to send(100 Views Minimum)" required="true"/><br><br>
Reward per view<input type="text" name="pays" min="0.00001" placeholder="Enter reward per view(0.00001 '.$siteData['currency'].' Minimum)" required="true"/><br><br>
<input type="submit" name="submit" class="NormButton" Value="Submit" /> ' ;
}
?>
</center>
</form>
</div>
<?php
require_once '../main/footer.php';
$dBase->closeDatabse();
}else{
header('location: index.php');
}
echo $siteConstant->getTail();
Why is your where clause is before SET
Check this
"UPDATE members SET balance=($userData['balance'] - $_POST['views'] * $_POST['pays']) WHERE username=$_SESSION['username']"

Categories