update page - update all records with the same data - php

I've small php project to list Covid-Test Labs, When you press the Update button for one of the records in the list of records, the data modification window opens, and when you enter it, the entries of other records are updated with the same information
How to solve this issue ?
<!-- Update Form -->
<form style = "font-size : 30px">
<input type="text" id="lab_name" class="fadeIn second" name="lab_name" placeholder="Laboratory Name" required>
<input type="text" id="test_price" class="fadeIn second" name="test_price" placeholder="Test Price" required>
<input type="text" id="lat" class="fadeIn second" name="lat" placeholder="Lat" required>
<input type="text" id="lon" class="fadeIn second" name="lon" placeholder="Lon" required>
<div class="dropdown">
<select name="lab_city" class="dropdown" required>
<option value="">--- Select City---</option>
<option value="Khartoum">Dubai</option>
<option value="Bahri">Bahri</option>
<option value="Omdurman">Paris</option>
</select>
<input type="file" name="image" id="image" required>
</div>
<input type="submit" id="submit" class="fadeIn fourth" value="Update">
</div>
</div>
</form>
<section>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "covidsd";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$lab_id = $_GET['lab_id'];
$lab_name= mysqli_real_escape_string($link, $_REQUEST['lab_name']);
$lab_city = mysqli_real_escape_string($link, $_REQUEST['lab_city']);
$test_price= mysqli_real_escape_string($link, $_REQUEST['test_price']);
$lat= mysqli_real_escape_string($link, $_REQUEST['lat']);
$lon= mysqli_real_escape_string($link, $_REQUEST['lon']);
$image= mysqli_real_escape_string($link, $_REQUEST['image']);
//$ServerURL = "http://192.168.43.236/AndroidUploadImage/$ImagePath";
$sql = "UPDATE laboratories SET lab_name ='$lab_name',lab_city ='$lab_city', test_price= '$test_price', lat='$lat', lon= '$lon', image= '$image' ". "WHERE lab_id='$lab_id' ";
if(mysqli_query($link, $sql)){
$message = "Laboratory has been updated successfully";
echo "<script type='text/javascript'>alert('$message');</script>";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
I tried many solutions but not working

Each record in your table must have a unique id field. You will retrieve this field when loading your list. When modifying a record, you will send that id field again to PHP. Inside PHP you will use it in your SQL WHERE IdField=$ID.
You are using variable $lab_id In your PHP code $lab_id = $_GET['lab_id']; and this means that you have an input on your form with name lab_id. I can't see that input it in your HTML so you need to add it like that :
<form style = "font-size : 30px">
<input type="hidden" id="lab_id" name="lab_id" Value = "$lab_id">
<input type="text" id="lab_name" class="fadeIn second" name="lab_name" placeholder="Laboratory Name" required>
...............
...............
</form>
In your PHP code you must decide what kind of request you will accept either POST or GET. Now you are using a mix of $_GET and $_REQUEST. If you are modifying or inserting data, it will better to use $_POST. Getting variables is PHP code will looks like :
$lab_id = $_POST['lab_id'];
$lab_name= mysqli_real_escape_string($link, $_POST['lab_name']);
If you are using a framework which do the request, you can check it to make sure if it is sending lab_id, if it sends lab_id you will not need it inside form. You may also adjust the request type in your framework if you are using a one.

Related

Prevent mysql query without input

I have a piece of code which inserts user's input into a database:
Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("DB status: connection failed: " . $conn->connect_error);
} else {
echo "DB status: connected";
}
?>
<html>
<h1>Add data</h1>
<form method="post">
<p>Name: <input type="text" name="name"></p>
<p>Goals scored in:</p>
<p>14/15 <input type="text" name="14"></p>
<p>15/16 <input type="text" name="15"></p>
<p>16/17 <input type="text" name="16"></p>
<p>17/18 <input type="text" name="17"></p>
<button type="submit" name="save">save</button>
</form>
<?php
$sql = "INSERT INTO `goals` (`Name`, `14/15`, `15/16`, `16/17`, `17/18`) VALUES ('".$_POST["name"]."', '".$_POST["14"]."', '".$_POST["15"]."', '".$_POST["16"]."', '".$_POST["17"]."')";
$result = mysqli_query($conn,$sql);
?>
The problem is that when I load the page for the first time, it already sends 0's to the database. How can I prevent this from happening?
Thanks a lot for helping!
add an action to your form and use that to send the sql query. You should probably also be using form validation requiring some fields like name to be filled out.
<p>Name: <input type="text" name="name" required></p>
Calling a particular PHP function on form submit
Add this piece of code at the beginning to fix the issue:
if (isset($_POST['submit']))
{
}

Php form data won't insert data on my PhpMyAdmin database

I've been trying to resolve this but i can't see the error. please help me. This is my code so far. What should i do? i checked every detail but cant find it. when i click the button, there's no error and it will return in the reservation.php page. I also have a "res_id" in my database which is auto increment. how should i include it in the insert statement?
Php code:
<?
$conn = mysqli_connect("localhost","root","") or die(mysql_error());
mysqli_select_db("hoteldb",$hoteldb) or die("no db found");
if(isset($_POST['confirm'])){
$fname= $_POST['fname'];
$lname= $_POST['lname'];
$contact= $_POST['contact'];
$username= $_POST['username'];
$password= $_POST['password'];
$email= $_POST['email'];
$address= $_POST['address'];
$checkin= $_POST['checkin'];
$checkout= $_POST['checkout'];
$query="INSERT INTO reservation(fname,lname,contact,username,password,email,address,checkin,checkout)
VALUES ('$fname','$lname','$contact','$username','$password','$email','$address','$checkin','$checkout')";
mysql_query($query,$conn);
mysqli_close($conn);
}
?>
Html code:
<form action="reservation.php" method="post">
<div>
<label>Title:</label>
<select name="title">
<option value="ms">Ms.</option>
<option value="mr">Mr.</option>
<option value="mrs">Mrs.</option>
</select>
</div>
<div >
<label>First Name:</label>
<input type="text" name="fname">
</div>
<div>
<label>Last Name:</label>
<input type="text" name="lname">
</div>
<div>
<label>Phone Number:</label>
<input type="text" name="contact">
</div>
<div>
<label>Username:</label>
<input type="text" name="username" >
</div>
<div >
<label>Password:</label>
<input type="password" name="password" >
</div>
<div >
<label>Email Address:</label>
<input type="text" name="email" >
</div>
<hr>
<h5>Address</h5>
<div >
<label>Full Address:</label>
<input type="text" name="address" >
</div>
<hr>
<h5>Date</h5>
<div >
<legend>Check-in</legend>
<input type="date" name="checkin">
<legend>Checkout </legend>
<input type="date" name="checkout">
</div>
<input type="submit" name="confirm">
</form>
or is it because of the date picker? if so, can you please teach me how to use the date picker? its my first time using it. Thank you! :)
try to get error description: (add after $query's definition)
if (!mysqli_query($conn, $query)) {
echo("Error description: " . mysqli_error($conn));
}
Try turning on PHP errors to not get just an empty page.
http://php.net/manual/en/mysqli.query.php
mysql_query($query, $conn);
this should be
mysqli_query($conn, $query);
I also have a "res_id" in my database which is auto increment. how should i include it in the insert statement?
Since it's set to "auto increment", you dont need to do anything with it
Also, try looking at PDO, it's safer and takes less code to use.
When you connect to the database you use mysql, after this you are trying to insert data using mysqli_query, it is impossible. You have to replace
mysql_query($query,$conn);
with
mysqli_query($conn, $query);
so your php will look like this
<?
$conn = mysqli_connect("localhost","root","") or die(mysql_error());
mysqli_select_db("hoteldb",$hoteldb) or die("no db found");
if(isset($_POST['confirm'])){
$fname= $_POST['fname'];
$lname= $_POST['lname'];
$contact= $_POST['contact'];
$username= $_POST['username'];
$password= $_POST['password'];
$email= $_POST['email'];
$address= $_POST['address'];
$checkin= $_POST['checkin'];
$checkout= $_POST['checkout'];
$query="INSERT INTO reservation(fname,lname,contact,username,password,email,address,checkin,checkout)
VALUES ('$fname','$lname','$contact','$username','$password','$email','$address','$checkin','$checkout')";
mysqli_query($conn, $query);
mysqli_close($conn);
}
?>
This is main problem.
You can use this templates any time u need insert something in your database
https://www.w3schools.com/php/php_mysql_insert.asp
If u want to use mysqli go to
Example (MySQLi Procedural) part
But I would recommend to use PDO;
The error in Mysqli_select_db statement.
You need correct your statement.
mysqli_select_db("hoteldb",$hoteldb) or die("no db found");
insted of this
mysqli_select_db($conn,"hoteldb") or die("no db found");

mysql doesn't update information from html/php

The problem I have: I made a "contact" form, which should send data to my database. All works good, no errors after I access the page from localhost, shows the result I wanted to see, but the database (localhost/phpmyadmin/..) doesn't update with any info.
This is my PHP:
if(isset($_POST['insert']))
{
$hostname = 'localhost';
$username = 'root';
$password = '';
$databaseName = 'nig';
$Nume = $_POST['nume'];
$Email = $_POST['email'];
$Telefon = $_POST['telefon'];
$Subiect = $_POST['subiect'];
$Mesaj = $_POST['mesaj'];
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
$query = "INSERT INTO `amar` (`nume`, `email`, `telefon`, `subiect`, `mesaj`) VALUES ('$Nume','$Email','$Telefon','$Subiect','$Mesaj')";
$result = mysqli_query($connect,$query);
if($result)
{
echo 'Mesaj trimis.';
}else{
echo 'Mesaj netrimis';
}
mysqli_free_result($result);
mysqli_close($connect);
This is my HTML:
<form action="insert2.php" action="post">
<form role="form">
<div class="form-group">
<label for="nume">Nume complet</label>
<input type="text" class="form-control" name="nume">
</div>
<div class="form-group">
<label for="email">Adresa e-mail</label>
<input type="text" class="form-control" name="email">
</div>
<div class="form-group">
<label for="telefon">Telefon</label>
<input type="text" class="form-control" name="telefon">
</div>
<div class="form-group">
<label for="subiect">Subiect</label>
<input type="text" class="form-control" name="subiect">
</div>
<div class="form-group">
<label for="mesaj">Mesaj</label>
<textarea class="form-control" name="mesaj" rows="8"></textarea>
</div>
<input type="submit" name="insert" class="btn btn-theme" value="insert"></button>
</form>
And the result should be data in my MySQL. but the database isn't getting any data, what am I doing wrong?
You have two form tags, one inside the other.
Change this....
<form action="insert2.php" action="post">
<form role="form">
To this...
<form action="insert2.php" action="post">
Also, please note, your PHP code is open to SQL injection. Never trust user input. Always validate and/or escape user entered data prior to using it in a query. Or better yet, used prepared statements or stored procedures.
Update 1:
OK, sorry to hear this is not working. Please add the following mysqli error debugging so we can see what is happening.
Change this...
$result = mysqli_query($connect,$query);
To this...
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$result = mysqli_query($connect,$query)
if (!$result)) {
printf("Errormessage: %s\n", mysqli_error($connect));
}
Then run the code and see if you get any errors that may help us.
Update 2:
OK, try another piece of debugging.
After this...
$query = "INSERT INTO `amar` (`nume`, `email`, `telefon`, `subiect`, `mesaj`) VALUES ('$Nume','$Email','$Telefon','$Subiect','$Mesaj')";
Add this...
die($query);
Save and run the code.
You will be given a SQL query. Copy and paste that SQL query and run it in your database management tool (phpMyAdmin for example). See if the record is added when you manually run the query or if you are given any errors.
Let us know the outcome.

Inserting HTML Form data into MySQL with PHP

I'm trying to make a simple message board MySQL database where you can write a review and submit it via an HTML form on one page and view all of the reviews on a separate page once you've submitted your review.
My problem is two of the fields from the HTML form are not being inserted into my MySQL database which results in my view all reviews page to be missing the Name and Title.
Link to what the "Read all Reviews" page looks like.
The code works without any issue when I tested it doing MySQL queries with just PHP but I need my HTML form to work.
HTML form:
<form action ="process.php" method = "post">
<fieldset>
<legend>Review Field</legend>
Reviewer Name: <br />
<input type="text" name "name" id = "name"><br />
Title of Review:<br />
<input type="text" name "title" id = "title"><br />
Enter your review below:
<!--Textbox start-->
<textarea name="body" id = "body" rows="10" cols="100">
</textarea>
<!--Textbox end-->
<br />
<input type="submit" name = "submit" id="submit">
<br />
</fieldset>
</form>
Code for process.php:
<?php // Create a database connection.
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "password";
$dbname = "ya_reviews";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
//Test if connection occurred.
if (mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
//Perform database query
$name = $_POST['name'];
$title = $_POST['title'];
$body = $_POST['body'];
//This function will clean the data and add slashes.
// Since I'm using the newer MySQL v. 5.7.14 I have to addslashes
$name = mysqli_real_escape_string($connection, $name);
$title = mysqli_real_escape_string($connection, $title);
$body = mysqli_real_escape_string($connection, $body);
//This should retrive HTML form data and insert into database
$query = "INSERT INTO reviews (name, title, body)
VALUES ('".$_POST["name"]."','".$_POST["title"]."','".$_POST["body"]."')";
$result = mysqli_query($connection, $query);
//Test if there was a query error
if ($result) {
//SUCCESS
header('Location: activity.php');
} else {
//FAILURE
die("Database query failed. " . mysqli_error($connection));
//last bit is for me, delete when done
}
mysqli_close($connection);
?>
View all Reviews:
<?php
//This will fetch the data from the database
$query = "SELECT * FROM reviews";
$result = mysqli_query($connection, $query);
//Test if there was a query error
if (!$result) {
die("Database query failed.");
}
// This will let me display the data.
// The loop will be spilt so I can format with HTML
while ($row = mysqli_fetch_assoc($result)) {
//output data from each row
?>
Name: <?php echo $row["name"] . "<br />"; ?>
Title: <?php echo $row["title"] . "<br />"; ?>
Review: <?php echo $row["body"] . "<br />";
echo "<hr>"; ?>
<?php
} ?>
Note: I connected to the database with the same code seen in process.php before the above code, I excluded it to save space.
Your HTML attribute syntax is incorrect. Its missing = sign between attribute and value.
Change name "name" to name="name" and name "title" to name="title"
<input type="text" name="name" id = "name"><br />
Title of Review:<br />
<input type="text" name="title" id = "title"><br />
Also during insert you aren't using escaped values.
Use $name instead of $_POST["name"] in insert query. Same goes for title and body values.
The problem is that the name attribute is not correct in HTML.
<input type="text" name="name" id = "name"><br />
<input type="text" name="title" id = "title"><br />
I think you messed up with syntax of HTML
<form action ="process.php" method = "post">
<fieldset>
<legend>Review Field</legend>
Reviewer Name: <br />
<input type="text" name="name" id = "name"><br />
Title of Review:<br />
<input type="text" name="title" id = "title"><br />
Enter your review below:
<!--Textbox start-->
<textarea name="body" id = "body" rows="10" cols="100">
</textarea>
<!--Textbox end-->
<br />
<input type="submit" name = "submit" id="submit">
<br />
</fieldset>
</form>
It will work surely!
Yo, you're just missing some syntax, therefore creating errors when it comes to gathering the data from those elements,
<input type="text" name "title" id = "title">
You're missing the "=" sign from the name parameter

Joining two strings to create one variable in php

Ok so I have a registration form for users to register and it works fine in that when it submits it enters into my database. I want to add a feature that only users with a certain domain address can register and after looking this up the simplest way I can see to do it is to use a drop down menu with a list of the available domains accepted. My issue is that when I try and run the concatenation function to join them upon entry they are not being joined and added to the database correctly below is my HTML form and my php code.
<form name='registration' method="post" action="registerAdmin.php">
<label for="adminName"> Name: </label>
<input name="adminName" id="a" size="27" required/>
<br/>
<label for="adminEmail"> Email Address: </label>
<input type="text" name="adminEmail" id="a" size="15" required/> <select style="height:27px;width:5;" name="adminDomain"><option value="#ucc.ie">#ucc.ie</option></select>
<br/>
<label for="adminUsername"> Username: </label>
<input name="adminUsername" id="b" size="27" required/>
<br/>
<label for="password"> Password: </label>
<input type="password" name="adminPassword" id="b" size="27" required/>
<br/>
<br/>
<input id="boo" type="submit" name="button" value="Register" class="btn btn-danger btn-lg"/>
</form>
And my PHP code:
$servername = "localhost";
$username = "********";
$password = "********";
$dbname = "********";
// FORM HANDLING
$aName = $_POST["adminName"];
$aEmail = $_POST["'adminEmail"];
$aUsername = $_POST["adminUsername"];
$aPassword = $_POST["adminPassword"];
$aEmail .= $_POST["adminDomain"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if (mysqli_connect_error()) {
die("Database connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO administrators (`adminName`, `adminEmail`, `adminUsername`, `adminPassword`)
VALUES ('".$aName."','".$aEmail."','".$aUsername."','".$aPassword."')";
if ($conn->query($sql) === FALSE) {
function died($error) {
// your error code can go here
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
} else {
echo "Account has successfully been created, please click the link below to return to the login screen!";
}
$conn->close();
?>
Everything bar the email address gets entered into the database correctly.
There is an extra "'" in the below statement:
$aEmail = $_POST["'adminEmail"]; it has to be `$aEmail = $_POST["adminEmail"];`
This should sort out the issue.

Categories