MAX ID count only works every other time - php

Problem:
I want to get the MAX "SID" from my Database and add one. I handle the input via an Form that i submit through the HTTP Post Method. I get the current MAX "SID" from my database, then i put the value into an HTML input field and add one. For some reason this just works every other time. So the output i get is:
Try = 1
Try = 1
Try = 2
Try = 2
and so on. Would be nice if someone could point me in the right direction.
PHP get MAX(ID):
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "soccer";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$sql = "SELECT MAX(SID) FROM spieler";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$lastID = $row["MAX(SID)"];
}
}
mysqli_close($conn);
PHP insert in database:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "soccer";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?><br><?php
$sql = "INSERT INTO spieler VALUES ('$sid', '$name', '$verein',
'$position', '$einsaetze', '$startelf', '$tore',
'$torschuesse', '$eigentore', '$vorlagen', '$elfmeter',
'$verwandelt', '$gegentore', '$gelb',
'$rot', '$fouls', '$zweikampf', '$pass', '$note')";
if(mysqli_query($conn, $sql)){
echo "Success";
}else{
echo "Failed" . mysqli_error($conn);
}
mysqli_close($conn);
HTML & PHP Input Field:
<tr>
<td><input id="SID" name="SID" readonly value="<?php echo $lastID += 1;
?>"></td>
</tr>
Screenshot of the page:
The paragraph "Spieler ID:" is where I put the "SID" so that everytime the page loads the next free ID gets automatically loaded into the input field.

I want to get the MAX "SID" from my Database and add one
No. You don't. You really, really don't.
This is the XY Problem.
You can do it by running a system wide lock and a autonomous transaction. It would be a bit safer and a lot more efficient to maintain the last assigned value (or the next) as a state variable in a table rather than polling the assigned values. But this still ignores the fact that you going to great efforts to assign rules to what is a surrogate identifier and hence contains no meaningful data. It also massively limits the capacity and poses significant risks of both accidental and deliberate denial of service.
To further compound the error here, MySQL provides a mechanism to avoid all this pain out of the box using auto-increment ids.
While someone might argue that these are not portable, hence there may be merit in pursuing another solution, that clearly does not apply here, where your code has no other abstraction from the underlying DBMS.

Related

How to fix php query in web application search bar and display results

I have a search box in the navigation bar of my web application that appears on every web page. I have a query that is supposed to pull results from my database based on the text the user enters in the search box but at the moment it doesn't show any results.
My web application is essentially a post it board for events so I want a user to be able to search for an event and then have that event displayed in either a table or to take it to the page of the event itself whichever is easier. I am using Netbeans as my IDE and my database is a MariaDB in XAMPP. My web application is just locally hosted for now. I currently have a query that should search the database but I think the output of the query or the result is wrong. I'm not great at PHP but just need to do this as it is in every page of the web application.
The code of the search bar on every page:
<form action="search.php" method="post">
<input type="text" name="search" placeholder="Search for an event..">
<input type="submit" value="Search">
</form>
Then the search.php file looks like this:
<?php
$search = filter_input(INPUT_POST, 'search');
$companyname = filter_input(INPUT_POST, 'companyname');
$eventname = filter_input(INPUT_POST, 'eventname');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "fyp";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "SELECT eventname FROM event WHERE eventname LIKE '%$search%'";
if ($conn->query($sql) === TRUE) {
echo "Result Found";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
At the moment, it just comes up saying "Connected successfullyError: SELECT eventname FROM event WHERE eventname LIKE '%Golf%'". I have an event called "SHARE Golf Classic" in the database so that's what I'm testing with currently. I would like to navigate to a page called Event.php and display the results in either a table or else fill labels or textboxes with the details of the event. The event table consists of eventid, eventname, eventtype, charityid, contactdetails, location and date.
Determining errors of objects (Mysqli) can be difficult, that's why you should use try-catch approach instead. Your code could look like this:
<?php
$search = filter_input(INPUT_POST, 'search');
$companyname = filter_input(INPUT_POST, 'companyname');
$eventname = filter_input(INPUT_POST, 'eventname');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "fyp";
try {
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT eventname FROM event WHERE eventname LIKE '%$search%'";
if (($result = $conn->query($sql)) === true) {
var_dump($result)
}
} catch (mysqli_sql_exception $e) {
var_dump($e)
} finally {
$conn->close();
}
Please bear in mind that using parameters from POST request in the query like this can be dangerous. I would suggest looking into a different MySQL client for PHP (PDO) and use prepared statements instead.
The code example above is also using finally, which was added in PHP 5.5, make sure your version is this or above (currently supported PHP versions are 7.2 and 7.3 - you should be always up to date).

PHP code for a HTML form sending data to a MySQL database?

I have this form:
<form action="contactus.php" method="post">
<select name="formTitle">
<option value="">Select...</option>
<option value="M">Mr</option>
<option value="F">Mrs</option>
</select>
<p><b>Name</b></p>
<input type="text" name="formName" maxlength="50"/>
<p><b>Enquiry</b></p>
<input type="text" name="formEnquiry" maxlength="500"/>
</select>
<p><input type="submit" name="formSubmit" value="Submit"/></p>
And I have a MySQL database (called 'contacts') with a table (called 'enquiries') with three columns; 'Title', 'Name', 'Enquiry'.
The database has no password or anything. It's just a localhost with a 'root' password.
What kind of PHP would I need to send the data from this HTML form to the MySQL database?
I can help you in this problem.
So, just add the following code to your php file contactus.php.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "contacts";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['formSubmit'])) {
$formTitle = $_POST['formTitle'];
$formName = $_POST['formName'];
$formEnquiry = $_POST['formEnquiry'];
$sql = "INSERT INTO enquiries (Title, Name, Enquiry) VALUES ('$formTitle', '$formName', '$formEnquiry')";
$conn->query($sql);
?>
I hope this will solve your problem.
SIMPLE ANSWER: MySQL
A LITTLE BIT MORE DEVELOPED ANSWER:
MySQL is in basic terms the combination of PHP and SQL to create an easy way to do various actions to a database, which include:
Create table
Query table
Update table
and much more
There are variations of MySQL, including MySQLi and MySQL (PDO).
an example of connecting to your database via MySQL (PDO) would be:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$myDB = "databasename";
try {
$conn = new PDO("mysql:host=$servername;dbname=$myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
//insert code there that you want to execute...
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
you mentioned that you don't have a password, so you might just leave the "password" slot empty ("") I suppose, though this is very insecure and I recommend you place a password.
In the code above, there is a comment that says:
//insert code there that you want to execute...
Here you would include code that would probably do actions similar to the ones mentioned above (query table, update table, etc). An example of code similar to that would be:
//htmlspecialchars takes out special characters that might
//exist in the posted information if someone were trying
//to hack your site via sql injection
$formTitle = htmlspecialchars($_POST['formTitle']);
$formName = htmlspecialchars($_POST['formName']);
$formEnquiry = htmlspecialchars($_POST['formEnquiry']);
$sql = "INSERT INTO enquiries (Title, Name, Enquiry) VALUES (formTitleBinded, formNameBinded, formEnquiryBinded)";
$sqlPrepared = $conn->prepare($sql);
$sqlPrepared->bindParam(':formTitleBinded',$formTitle);
$sqlPrepared->bindParam(':formNameBinded',$formName);
$sqlPrepared->bindParam('formEnquiryBinded',$formEnquiry);
$sqlPrepared->execute();
The previous code both sanitizes your input and inserts a row into your table with that information.
Let me know if that helped!
EDITED: My answer has been edited with parameter binding included to prevent SQL Injection.

Wordpress - Assign Student Roll Numbers on Form Submission

I am working on an academy website here at www.grmaedu.com
Web Specs: Built on Wordpress with the following plugins, Visual Form Builder Pro & Revolution Slider
So i have managed to do 90% of the work. My query is I want to assign automatic roll numbers to students who are submitting the application form here at www.grmaedu.com/application
Here are the remaining things I want to do:
Automatically assign Roll Number to students "after or on " form submission
Submit the form to the concerned mySql Database, Right now it emails correctly to the designated email address with no issues. All thanks to Visual Form Builder Pro
The date picker field is not working in the application form(I even updated my jQueryUI file)
I hope the provided details are enough for the solution.
I finally figured a way out. Here are the steps which i performed.
I installed a WP Plugin named Contact Form DB. This plugin saves all the form submitted values and stores them in a mySQL database.
I opened up phpmyadmin to see how it was stored and found it in one of the tables. I noticed that each entry had an unique id number. That is what I was trying to do. This plugin made it easier for me.
Then i created a Page template file name rollnumber.php and inserted the following code in
<?php
/* Define Connection properties */
$servername = "localhost";
$username = "grmaedu_wp2";
$password = "******";
$dbname = "grmaedu_wp2";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT entries_id FROM `wp_vfb_pro_entries` ORDER BY entries_id DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$a = $row["entries_id"];
$a++;
echo "<h3>Your Roll Number assigned is: " . $a . "</h3>";
//echo "id: " . $row["entries_id"] . "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
So now when the page loads it automatically fetches the unique id and adds 1 to the last submitted id and voila a new roll number is generated.
Index key is the best option to set as roll number. because it is unique and then you can get user data directly form this id.
<?php
/* Define Connection properties */
$servername = "localhost";
$username = "grmaedu_wp2";
$password = "******";
$dbname = "grmaedu_wp2";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT entries_id FROM `wp_vfb_pro_entries` ORDER BY entries_id DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
echo "<h3>Your Roll Number assigned is: " . mysqli_insert_id() . "</h3>";
//echo "id: " . mysql_insert_id() . "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>

how to do multiple if statemnts in php based on a criteria

I have a database named hrRecords and a table named employee in that table. It has a field named contract_end. In that field, I have the contract info of the employee specifically the duration of said contract (datetime).
What I want to achieve is to check that info to see when the contract is going to come to an end and if it is display a message saying so.
I am very new to php and I tried something but I am totally lost I was wondering if I could get some guidance of some sort thank you for your support:
<?php
$employee1= mysql_real_escape($_GET["employee1"]);
$DataBase = "hrRecords";
mysql_connect("server","username", "password") or die(mysql_error());
mysql_select_db($DataBase) or die(mysql_error());
$query = SELECT contract_end From hrRecords
// current date being compared
if(contract_end== date(Y-m-d) {
echo "something"
}
else {
echo " employe name , Your contract will expire in x amount of days "
}
/* This is the point where everything becomes fuzzy because im thinking there has to be some other way to do this for all the employees */
fist stop using mysql it has been depreciated
use either mysqli or pdo. I will show you how to do it with mysqli
<?php
$employee1= mysql_real_escape($_GET["employee1"]); // i am not sure why you are doing this since you are not using this any where
$DataBase = "hrRecords";
$ServerName = "server";
$UserName = "username";
$Password = "password";
$mysqli = new mysqli($ServerName, $UserName, $Password,$DataBase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// since i don't know all of colum names i am making them up
$stmt= $mysqli->prepare("SELECT contract_end employe_name From hrRecords");
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($contract_end, $employe_name)
while($stmt->fetch()) { // this will go thorough all of the records
// current date being compared
if($contract_end== date(Y-m-d) {
echo "something"
} else {
// you need some more code here to find x
echo " $employe name , Your contract will expire in x amount of days "
}
}
i don't know if this will help you at all. you did not have enough info for a better answer

How to fetch data as it is from MySql Database using PHP

I am trying to fetch Data from MySQL Database using PHP script from Server. I am able to get Data from Database, but I am not getting the exact string present in Database. In the result obtained the spaces between words get trimmed and result does not match with String present in Database.
For Example:
The value inserted to Database is as shown Below:
SELENIUM INTERVIEW QUESTIONS:
What is Selenium?
Selenium is a set of tools that supports rapid development of test automation scripts for web based applications. Selenium testing tools provides a rich set of testing functions specifically designed to fulfill needs of testing of a web based application.
What are the main components of Selenium testing tools?
Selenium IDE, Selenium RC and Selenium Grid
The result obtained from the Database query shows the data as:
SELENIUM INTERVIEW QUESTIONS:What is Selenium?Selenium is a set of tools that supports rapid development of test automation scripts for web basedapplications. Selenium testing tools provides a rich set of testing functions specifically designed to fulfill needs of testing of a web based application.What are the main components of Selenium testing tools?Selenium IDE, Selenium RC and Selenium Grid
Can any one please let me know what changes should I make in my script to obtain data as it is shown in database from my query. I am using mysql_real_escape_String while inserting and I am using stripslashes while retrieving data from database.
Below is my PHP script:
Insert Script:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "iFocusBlogs";
$obtainedName = urldecode($_POST['enteredName']);
$obtainedUserName = urldecode($_POST['enteredUserName']);
$obtainedsubjectText = urldecode($_POST['subjectText']);
$obtaineddetailsText = urldecode($_POST['detailsText']);
$status = urldecode($_POST['status']);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$obtainedsubjectText = $conn->real_escape_string($obtainedsubjectText);
$obtaineddetailsText = $conn->real_escape_string($obtaineddetailsText);
$sql = "INSERT INTO AndroidTable (Name, UserName, Subject, Details, Status)
VALUES ('$obtainedName', '$obtainedUserName', '$obtainedsubjectText', '$obtaineddetailsText', '$status')";
mysqli_commit($conn);
if ($conn->query($sql) === TRUE) {
echo "Inserted Post sent to Moderator for Approval. Once approved from Moderator, Post will be displayed";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
fetch Script:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "iFocusBlogs";
$obtainedUserName = 1;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql="SELECT Name, Subject FROM AndroidTable WHERE Status ='" .$obtainedUserName. "'";
$result=mysqli_query($conn,$sql);
while ($row = mysqli_fetch_row($result)) {
foreach($row as $rows){
for($i=0;$i<count($rows);$i++){
echo stripslashes($rows) . " ";
$n=$i;
}
}
echo "<br/>";
}
$conn->close();
?>
Please let me know what mistake am I doing in my script. All suggestions are welcome. If more information required please let me know. Thanks in advance.
You can use nl2br, which will convert new line characters to <br>, so wherever you are echoing, you just need to call nl2br function, see example below:
echo nl2br(stripslashes($rows)) . " ";
EDIT:
To get spaces instead of <br>, you can simply replace new line character \n with space, or anything you would like to replace with, see example below:
echo str_replace("\n", " ", stripslashes($rows))
EDIT 2:
echo stripslashes(str_replace(array('\r\n', '\n'), "<br>", $rows));

Categories