Why I can't Pass values to the database using php - php

I have built an ISBN generator using PHP. However, Once ISBN Number is generated it's not stored in the database.
Here is the index.php
<form id="isbn-form" action="generate-isbn.php" method="POST">
<label for="title">Book Title:</label><br>
<input type="text" id="title" name="title"><br>
<label for="author">Author:</label><br>
<input type="text" id="author" name="author"><br>
<button type="submit">Generate ISBN</button>
</form>
<script>
const form = document.getElementById("isbn-form");
form.addEventListener("submit", async (event) => {
event.preventDefault();
// Get the form data
const formData = new FormData(form);
// Send a POST request to the server
const response = await fetch("generate-isbn.php", {
method: "POST",
body: formData,
});
// Get the generated ISBN number
const data = await response.json();
const isbn = data.isbn;
// Display the ISBN number
alert(`Your ISBN number is: ${isbn}`);
});
</script>
Here is the isbn.php
function generate_unique_isbn() {
// Generate a unique ISBN
do {
// Generate the first three digits (ISBN agency)
$isbn = rand(100, 999) . "-";
// Generate the language code
$isbn .= rand(0, 9) . "-";
// Generate the book identifier using a cryptographically secure random number generator
$isbn .= bin2hex(random_bytes(4)) . "-";
// Calculate the check digit
$check_digit = 0;
for ($i = 0; $i < strlen($isbn); $i++) {
if ($i % 2 == 0) {
$check_digit += (int)$isbn[$i];
} else {
$check_digit += 3 * (int)$isbn[$i];
}
}
$check_digit = 10 - ($check_digit % 10);
if ($check_digit == 10) {
$check_digit = 0;
}
$isbn .= $check_digit;
// Connect to the database
$conn = new mysqli("localhost", "root", "", "isbn");
// Check if the ISBN is already in the database
$result = $conn->query("SELECT * FROM books WHERE isbn = '$isbn'");
// Close the database connection
$conn->close();
} while ($result->num_rows > 0);
return $isbn;
}
Here is the generate-isbn.php
<?php
require "isbn.php";
header("Content-Type: application/json");
// Get the form data
$title = $_POST["title"];
$author = $_POST["author"];
// Generate a unique ISBN number
$isbn = generate_unique_isbn();
// Save the book to the database
$conn = new mysqli("localhost", "root", "", "isbn");
$conn->query("INSERT INTO books (isbn, title, author) VALUES ('$isbn', '$title', '$author')");
$conn->close();
echo json_encode(["isbn" => $isbn]);
?>
Why the values are not passing? Save the book to the database code in the generate-isbn.php. Values are generated but only one value is stored in the database. If I want to save the generated value in the database I have to delete the previous value that was stored in the database and run the script. Then it gets stored, After it doesn't store then I have to re-run the process delete the value an run the code. What could be the issue?

The id column in your books table is primary key but you also have to set it AUTO_INCREMENT. Then you can insert rows more than one.
To do this you have to first click change action.
Then check A_I checkbox in Structure panel.

Related

Using PHP, Unable to post inside of function call line, able to post outside of function call line [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 10 months ago.
I'm using PHP, HTML, and MySQL to create a web page that lets users create text posts. I would like to avoid js and ajax for now.
When calling the function "post" from (post.php) the system is unable to complete the post. Removing the function line in (includes/post.inc.php) lets the user post correctly. I want to have the function line so I can reference multiple methods on this file. What am I messing up for the call of this function?
Here is the relevant information from post.php
<?php
require 'includes/dbh.inc.php';
require 'includes/post.inc.php';
session_start();
date_default_timezone_set('America/Chicago');
.
.
echo '
<form action="'.post($conn).'" method="post">
<label for="text">New Post</label>
<input type="text" name="Text" placeholder="Write your post here">
<input type="hidden" name="Date" value="'.date("Y-m-d H:i:s").'">
<br>
<button type="submit" name="postSubmit">Post</button>
</form>
';
?>
Then here is the post function from includes/post.inc.php
<?php
function post($conn) { // deleting this line allows my code to run correctly
session_start();
if (isset($_POST['postSubmit'])) {
require 'dbh.inc.php';
$UserID = $_SESSION['UserID'];
$Date = $_POST['Date'];
$Text = $_POST['Text'];
$SectionID = 1;
// make a random value for $postID and then see if it exists in the DB
$PostIDLength = 11;
$PostIDString = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$PostIDDuplicate = true;
while ($PostIDDuplicate = true) {
$PostID = substr(str_shuffle($PostIDString), 0, $PostIDLength); //shuffle String, start with 0, 11 characters long
$PostIDSQL = "SELECT PostID FROM PostTable WHERE PostID = ?";
$PostIDStmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($PostIDStmt, $PostIDSQL)) {
exit();
}
else {
mysqli_stmt_bind_param($PostIDStmt, "s", $PostID);
mysqli_stmt_execute($PostIDStmt);
$PostIDResult = mysqli_stmt_get_result($PostIDStmt);
$PostIDResultCheck = mysqli_num_rows($PostIDResult);
if ($PostIDResultCheck <= 0) {
$PostIDDuplicate = false;
break;
}
else {
// repeat until you have a unique ID
}
}
}
$PostSQL = "INSERT INTO PostTable (PostID, UserID, SectionID, Date, Text) VALUES (?, ?, ?, ?, ?)";
$PostSTMT = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($PostSTMT, $PostSQL)) {
echo 'Error2';
}
else {
mysqli_stmt_bind_param($PostSTMT, "ssiss", $PostID, $UserID, $SectionID, $Date, $Text);
mysqli_stmt_execute($PostSTMT);
}
header('Location: ../home');
exit();
}
else {
header("Location: ../home.php?error");
exit();
}
}
You're not calling the post function on includes/post.inc.php with the submit, just declaring it.
I recommend to use an jquery/ajax call on form submit:
$('#postSubmit').on('click', function() {
var text = $("#Text").val();
var date= $("#Date").val();
var action = 'createpost';
$.ajax({
type: "POST",
url: 'includes/post.inc.php',
data: ({
action : action,
text : text,
date: date
}),
success: function(data) {
console.log("do something")
}
});
});
Just add Ids to the inputs and the submit button

Insert multiple forms into same table - only last form is inserted

I have 2 forms on my website. The first form is static (general information). The second one (project information) can be duplicated (with jQuery) if people want to insert multiple projects. If more than 1 project is submitted, only the last project is inserted in the database. Which is not how it should work. All project forms should be submitted. The form looks like this (with 2 projects):
PHP code:
<?php include './includes/database.php';
if(isset($_POST['submit'])){
$company_name = mysqli_real_escape_string($connection, $_POST['company_name']);
$contact_name = mysqli_real_escape_string($connection, $_POST['contact_name']);
$email_address = mysqli_real_escape_string($connection, $_POST['email_address']);
$phone_number = mysqli_real_escape_string($connection, $_POST['phone_number']);
$project_name = mysqli_real_escape_string($connection, $_POST['project_name']);
$house_amount = mysqli_real_escape_string($connection, $_POST['house_amount']);
$people_type = mysqli_real_escape_string($connection, $_POST['people_type']);
$delivery_date = mysqli_real_escape_string($connection, $_POST['delivery_date']);
//Set date
$signup_date = date('Y-m-d', time());
//Lowercase email
$email_address = strtolower($email_address);
mysqli_autocommit($connection, false);
$flag = true;
$query = "INSERT INTO developers_prospects (signup_date, company_name, contact_name, email_address, phone_number)
VALUES ('$signup_date','$company_name','$contact_name','$email_address','$phone_number')";
$result = mysqli_query($connection, $query);
if (!$result) {
$flag = false;
echo "Error details: " . mysqli_error($connection) . ".";
}
$query1 = "INSERT INTO developers_prospects_projects2 (company_name, project_name, house_amount, people_type, delivery_date)
VALUES ('$company_name','$project_name','$house_amount','$people_type','$delivery_date')";
$result = mysqli_query($connection, $query1);
if (!$result) {
$flag = false;
echo "Error details: " . mysqli_error($connection) . ".";
}
if ($flag) {
mysqli_commit($connection);
$success = "Bedankt $contact_name! We hebben je gegevens in goede orde ontvangen.";
header ("Location: index.php?success=".urlencode($success));
} else {
mysqli_rollback($connection);
$error = "Oeps. Sorry $contact_name! Er ging iets mis.";
header ("Location: index.php?error=".urlencode($error));
}
mysqli_close($connection);
}
?>
And the jQuery part of the code:
<script>
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".developers-signup-form-container"); //Fields wrapper
var add_button = $(".developers-signup-form-add"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$len= $(".developers-signup-form-container").children("div").length+1;
$(wrapper).append("<div class='developers-signup-form-wrapper'><a href='#' class='developers-signup-remove-field'>X Sluiten</a><label class='developers-signup-form-label'>Projectnaam:</label><input class='developers-signup-form-field' type='text' name='project_name' ><label class='developers-signup-form-label'>Aantal woningen:</label><input class='developers-signup-form-field' type='text' name='house_amount' ><label class='developers-signup-form-label'>Type bewoners:</label><input class='developers-signup-form-field' type='text' name='people_type' ><label class='developers-signup-form-label'>Gewenste afleverdatum:</label><input class='developers-signup-form-field' type='text' name='delivery_date' ></div>");} });
$(wrapper).on("click",".developers-signup-remove-field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
}) });
</script>
What am I doing wrong? Looking forward to your answers.
First of all all of your inputs that are added by jQuery have the same name (project_name, house_amount, people_type, delivery_date)
Then again your php code doesn't handle multiple insert of new projects.
Rename the inputs so they are declared as arrays
'<input class="..." name="projectName[]"/>'
or
'...<input class="..." name="projectName[' + index + ']"/>...'
where index will be a key in php array - you possibly could use x variable in your case
Then in your php script $_POST['projectName'] will be an array which you should loop through
Another way would be to name inputs like this:
'<input class="..." name="projects[' + index + '][projectName]" />
<input class="..." name="projects[' + index + '][house_amount]" />'
Then in $_POST['projects'] you will have multidimensional array and you could do something like this:
foreach ($_POST['projects'] as $projectKey => $project) {
$projectName = $project['projectName']; // don't forget to escape
$houseAmount = $project['houseAmount'];
//
// do insert to db
}

Validate promo code from MySql table and mark as "used" when form is submitted

I have an HTML form starting with an input field, where the user have the option to write a promo code to get some discount ....
What I am trying to do here. I need to create a keyup functionto check if the typed code is found in the MySql Promo Codes table.
If found, write something in the placeholder ...., else, write something else ....
Also if the form is submitted in need the PHP to write 'Yes' in the code corresponding MySql Used column...
<form id="form" class="form" name="RevitForm" action="form_revit_architecture_submitted" method="post" enctype="application/x-www-form-urlencoded" accept-charset="UTF-8">
<div class="field" style="background-color:#f3f3f3;">
<span id="promo-msg" style="color:#093; position:relative; bottom:3px; font-style:italic; font-size:13px">[HTML is replaced when successful.]</span>
<center><input style="font-family:Lato; text-align:center; max-width:200px;" type="text" id="PromoCode" name="PromoCode" maxlength="5" size="15px" placeholder="Promo Code"></center>
</div>
//other input fields
</form>
<!-- Promotion Code Match -->
<script>
$("#PromoCode").keyup(function() {
if ($(this).val().length == 5) {
//post the code and check the it in the MySql table thru the PHP file "request.php"
//if code found {write something in $(#promo-msg) } else {do something else}
}
});
</script>
And in the PHP in need to excute something like
<?PHP
$code = ucwords($_POST['PromoCode']);
$con=mysqli_connect("localhost","x","y","academy_database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$db_code = mysqli_query($con," SELECT * FROM `Promo Codes` WHERE (`Code` LIKE '".$code."') AND (`Used` <> 'Yes') ");
// if $code is found and the corresponding `Used` column does not == 'Yes' return as found
//else return as not found
?>
To do that, we need 2 files.
HTML, form + jQuery AJAX keyup event and check DB
PHP connect to DB to check the promo code
1.HTML
<html>
<head>
<title>Promo check</title>
<!-- load jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
//the min chars for promo-code
var min_chars = 10;
//result texts
var checking_html = 'Checking...';
//when keyup
$('#code').keyup(function(event){
//run the character number check
if($('#code').val().length == min_chars){
//show the checking_text and run the function to check
$('#Promo_code_status').html(checking_html);
check_code();
}
});
});
//function to check the promo code
function check_code(){
//get code
var code = $('#code').val();
//use ajax to run the check
$.post("check_code.php", { code: code },
function(result){
//if the result is 0
if(result == 0){
//show that the code is correct
$('#Promo_code_status').html(code + ' is correct.');
}else if(result == 1){
//show that the code is correct, but already has been used
$('#Promo_code_status').html(code + ' is already used correct.');
}else{
//show that the code is not correct
$('#Promo_code_status').html(code + ' is not correct.');
}
});
}
</script>
</head>
<body>
<input type='text' id='code'>
<div id='Promo_code_status'></div>
</body>
</html>
2.PHP: check_code.php
You will need to use your connection data ($host, $user, $pass, $dbdb) and maybe change the table & field names.
<?php
//connect to database
$user = "";
$pass = "";
$host = "";
$dbdb = "";
$connect = mysqli_connect($host, $user, $pass, $dbdb);
if(!$connect)
{
trigger_error('Error connection to database: '.mysqli_connect_error());
}
//get the code
mysqli_real_escape_string($connect, $_POST['code']);
//mysql query to select field code if it's equal to the code that we checked '
$result = mysqli_query($connect, 'select promoCode, used from testtable where promoCode = "'. $code .'"');
$record = mysqli_fetch_array($result);
//if number of rows fields is bigger them 0 that means the code in the database'
if(mysqli_num_rows($result) > 0){
if($record['used'] == 0) {
//and we send 0 to the ajax request
echo 0;
} else{
//and we send 1 to the ajax request
echo 1;
}
}else{
//else if it's not bigger then 0, then the code is not in the DB'
//and we send 2 to the ajax request
echo 2;
}
?>
db_code = mysqli_query($con," SELECT * FROM `Promo Codes` WHERE (`Code` LIKE '".$code."') AND (`Used` <> 'Yes') ");
Do it like this:
"SELECT * FROM Promo Codes WHERE Code LIKE '$code' AND Used='yes' "
Also,To update parameter 'used':
UPDATE Promo Codes SET used='Yes' WHERE Code= '$code'
For the keyup function, you need to learn about AJAX requests. Since it's the medium for communicating with the server through the client
jQuery AJAX: http://api.jquery.com/jquery.ajax/

Making PhP code executes first before Javascript

<?PHP
//$errorMessage = "";
//$check = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
//===================================================
// GET THE QUESTION AND ANSWERS FROM THE FORM
//===================================================
$sID = $_POST['studentID'];
$sID = htmlspecialchars($sID);
$firstName = $_POST['firstName'];
$firstName = htmlspecialchars($firstName);
$lastName = $_POST['lastName'];
$lastName = htmlspecialchars($lastName);
$grade = $_POST['grade'];
$grade = htmlspecialchars($grade);
//var_dump($grade);
//============================================
// OPEN A CONNECTION TO THE DATABASE
//============================================
$user_name = "root";
$password = "";
$database = "surveyTest";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
//============================================
// GET THE LAST QUESTION NUMBER
//============================================
$SQL = "Select * FROM students WHERE SID='$sID'";
$result = mysql_query($SQL);
$db_field = mysql_fetch_assoc($result);
$studentID = $db_field['SID'];
var_dump($studentID);
//=========================================================
// Add a student to the students TABLE
//=========================================================
$SQL = "INSERT INTO students (SID, fName, lName, Grade) VALUES ('$sID', '$firstName', '$lastName', '$grade')";
$result = mysql_query($SQL);
//=============================================================
// SET Multiple rows IN THE answers TABLE for each question for a given student.
//=============================================================
/*$SQL = "Select * FROM tblquestions";
$result = mysql_query($SQL);
$numRows = mysql_num_rows($result); //return number of rows in the table
for ($i = 1; $i <= $numRows; $i++){
$qNum = 'q1';
$SQL = "INSERT INTO answers (QID, A, B, C, D, E, SID) VALUES ('$qNum', 0, 0, 0, 0, 0, '$sID')";
$question_Number = ltrim($qNum,'q');
$question_Number++;
$qNum ='q'.$question_Number;
$result = mysql_query($SQL);
}*/
mysql_close($db_handle);
print "The student with the following ID ".$sID. " has been added to the database";
}
else {
print "Database NOT Found ";
mysql_close($db_handle);
}
}
?>
<html>
<head>
<title>Survey Admin Page</title>
</head>
<body>
<FORM NAME ="setQuestionForm" METHOD ="POST" ACTION ="setStudent.php" id="sStudent">
<p>Enter student ID: <INPUT TYPE = 'TEXT' Name ='studentID' size="4"></p>
<p>Enter First Name: <input type="text" name="firstName" size="20"></p>
<p>Enter Last Name: <input type="text" name="lastName" size="20"></p>
<p>Select Grade: <select name = "grade">
<option value = "1">First Grade</option>
<option value = "2">Second Grade</option>
<option value = "3">Third Grade</option>
<option value = "4">Fourth Grade</option>
<option value = "5">Fifth Grade</option>
<option value = "6">Sixth Grade</option>
<option value = "7">Seventh Grade</option>
<option value = "8">Eighth Grade</option>
</select></p>
<INPUT TYPE = "submit" Name = "Submit1" VALUE = "Add Student">
</FORM>
<P>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(function(){
if ($('form').length > 0) {
$('form').submit(function(e){
var check = "<?php echo $studentID; ?>";
alert(check);
if (check != "")
{
alert ("This user already exists");
return false;
}
else
{
return true;
}
});
}
})
</script>
</body>
</html>
The above code is used to add students to a database, and I'm trying to do some form validation to avoid duplicated records. My problem is that I set a php variable $studentID that verifies whether the database contain the a student with the same ID.
However, when I try to add a duplicated record, it seems like my javascript code executes first and this can be observed by the alert message in the JQuery code that it shows a box of an empty string. Executing the code once more, do the correct thing.
Any help of how I can fix this?
On initial page load:
The process flow looks like this:
Server Side code -> sends data to client -> browser begins rendering and executing JS
On form Submit:
Client Executes code (javascript) -> Sends data to server -> Server gets data and processes
to change the way this works you would want to do an ajax or post form submit and on "success" then execute the above JavaScript. You can post to the same page or change it to a RESTful service.
Here are examples of AJAX and POST functions from jQuery:
AJAX
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
POST (JS)
$.post('ajax/test.html', function(data) {
$('.result').html(data);
});
Here is the result specifically for you, taking the two snippets above.
JavaScript/jQuery
$(function () {
if ($('form').length > 0) {
$('form').submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "YOUR-URL",
data: YOUR - FORM - DATA,
success: function (result) {
//result will contain the xml or JSON result of calling the FORM
var check = "<?php echo $studentID; ?>";
alert(check);
if (check != "") {
alert("This user already exists");
return false;
} else {
return true;
}
},
dataType: "XML-OR-JSON"
});
});
}
})

Having an Ajax Save button and save in database

I'm currently doing a form whereby customers will have to do the survey form, I'll have a AJAX "Save" button to allow me to save the data into database when the customers did not managed to finish the form itself and then when the customers login again, the form which they did halfway will pop out again and ask them to continue finish the survey form.
Is it possible where AJAX/javascript/jQuery can work with php codes in it (because of the insert query)?
Not very sure with AJAX and all so Thanks for helping!
This is for the "Save" button.
<input type="button" onClick="save();" value="Save">
This is the insert query whereby it will be inserted in database.
<?php
include("dbFunctions.php");
$idQuery = "SELECT id,question,input FROM db_ExtApp1.scFormLayout WHERE surveyID ='$lastID'";
$idResult = sqlsrv_query($conn, $idQuery);
while ($row = sqlsrv_fetch_array($idResult)) {
$fcID = $row['id'];
$question = $row['question'];
$surveyTitle = $_SESSION['surveyTitle'];
$input = $row['input'];
if (isset($_POST['qns' . $fcID])) {
$answer = implode(",", $_POST['qns' . $fcID]);
$newAns = str_replace($singleQuote,$changeQuote,$answer);
} else {
$newAns = '';
}
if (isset($_POST['others'.$fcID])) {
$others = $_POST['others' . $fcID];
$newOthers = str_replace($singleQuote,$changeQuote,$others);
}else {
$newOthers = 'N.A.';
}
$connectionInfo['ConnectionPooling']=0; // this creates a new connection on the next line...
$newconn = sqlsrv_connect($serverName, $connectionInfo);
if ($input != 'Normal text line, no input required*') {
$query = "INSERT INTO db_ExtApp1.scFormResult(surveyID, answer, others, title, question, name)
VALUES ('$lastID','$newAns','$newOthers', '$surveyTitle','$question', '$name')";
$status = sqlsrv_query($newconn, $query);
} }
if ($status === false) {
die(print_r(sqlsrv_errors(), true));
}
sqlsrv_close($conn);
You can use jquery $.ajax() to send data from client side to PHP. (eg)
$.ajax({
url : 'path/to/php/page',
data : { id : '1', name : 'name' },
dataType : 'JSON',
type : 'POST',
cache: false,
success : function(succ) {
alert(succ);
},
error : function(err) {
alert(err);
}
});
Then in PHP page, use $_POST[] to capture data and insert it into database.
$id = $_POST['id'];
$name = $_POST['name'];
Make sure you escape the values and make it safe for sql insert.

Categories