Insert, Update, Search in MySql database using PHP - php

This is my first post in this forum, despite being a devoted follower for years now.
I have built a simple system that registers lot numbers and their locations within a MySQL database through a PHP form.
Then i have this other form called "Errata Corrige" that I use to find and edit eventual mistaken entries.
It's search criteria is an (UNSIGNED INT UNIQUE) value named "lotto" and everything works (worked) like a charm under this circumstances.
Now the thing got a little tricky.
I found out that lot numbers (lotto) for work purposes are not always unique values, there might be more than one entry with the same number.
No problem making the "Insert" form or various counters work under this new circumstances, but it got really tricky within the EDIT functions.
This is my PHP code: `
<?php
$id = "";
$settore = "";
$ubicazione = "";
$numero = "";
$lotto="";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// connect to mysql database
try{
$connect = mysqli_connect($host, $user, $password, $database);
} catch (mysqli_sql_exception $ex) {
echo 'Error';
}
// get values from the form
function getPosts()
{
$posts = array();
$posts[0] = $_POST['id'];
$posts[1] = $_POST['settore'];
$posts[2] = $_POST['ubicazione'];
$posts[3] = $_POST['numero'];
$posts[4] = $_POST['lotto'];
return $posts;
}
// Search
if(isset($_POST['search']))
{
$data = getPosts();
$search_Query = "SELECT * FROM mappa WHERE lotto = $data[4]";
$search_Result = mysqli_query($connect, $search_Query);
if($search_Result)
{
if(mysqli_num_rows($search_Result))
{
while($row = mysqli_fetch_array($search_Result))
{
$id = $row['id'];
$settore = $row['settore'];
$ubicazione = $row['ubicazione'];
$numero = $row['numero'];
$lotto = $row ['lotto'];
}
}else{
echo 'Lotto non presente in archivio';
}
}else{
echo 'Error';
}
}
// Insert
if(isset($_POST['insert']))
{
$data = getPosts();
$insert_Query = "INSERT INTO `mappa`(`settore`, `ubicazione`, `numero`, `lotto` ) VALUES ('$data[1]','$data[2]',$data[3], $data[4])";
try{
$insert_Result = mysqli_query($connect, $insert_Query);
if($insert_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
$resInsert = "1 nuovo dato inserito correttamente!";
}else{
$resInsert = "Nessun dato inserito";
}
}
} catch (Exception $ex) {
echo 'Errore '.$ex->getMessage();
}
}
// Edit
if(isset($_POST['update']))
{
$data = getPosts();
$update_Query = "UPDATE `mappa` SET `settore`='$data[1]',`ubicazione`='$data[2]',`numero`=$data[3],`lotto`=$data[4] WHERE `id` = $data[0]";
try{
$update_Result = mysqli_query($connect, $update_Query);
if($update_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
$resAgg = "1 dato aggiornato correttamente!";
}else{
$resAgg = "Nessun dato aggiornato!";
}
}
} catch (Exception $ex) {
echo 'Error Update '.$ex->getMessage();
}
} ?>
`
HTML:
<form action="mod.php" method="post" class="form-horizontal form-bordered" style="text-align:center">
<div class="form-group has-error" style="padding-top:30px">
<label class="col-xs-3 control-label" for="state-normal">ID</label>
<div class="col-lg-3">
<input type="text" name="id" placeholder="ID" class="form-control" value="<?php echo $id;?>"> </div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="state-normal">Settore</label>
<div class="col-md-6">
<input type="text" name="settore" placeholder="Settore" class="form-control" value="<?php echo $settore;?>"> </div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="state-normal">Ubicazione</label>
<div class="col-md-6">
<input type="text" name="ubicazione" placeholder="Ubicazione" class="form-control" value="<?php echo $ubicazione;?>"> </div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="state-normal">Numero</label>
<div class="col-md-6">
<input type="text" name="numero" placeholder="Numero" class="form-control" value="<?php echo $numero;?>"> </div>
</div>
<div class="form-group has-success">
<label class="col-md-3 control-label" for="state-normal">Lotto</label>
<div class="col-md-6">
<input type="text" name="lotto" placeholder="Lotto" class="form-control" value="<?php echo $lotto;?>"> </div>
</div>
<div style="padding-top:16px">
<!-- Insert-->
<button type="submit" name="insert" value="Add" class="btn btn-effect-ripple btn-primary">Inserisci</button>
<!-- Update-->
<button type="submit" name="update" value="Update" class="btn btn-effect-ripple btn-info">Aggiorna</button>
<a> </a>
<!-- Search-->
<button type="submit" name="search" value="Find" class="btn btn-effect-ripple btn-success">Cerca</button>
</div>
</form>
While the lot number was unique everything worked like a charm.
Now that there are multiple data with the same lot number the code became obsolete since the "search" function only shows the last (greatest ID) data.
I have tried to work around a loop and tell the function to search every ID where lotto = lotto but it didn't work.
A simple solution would be obviously searching through ID instead of lotto but that is a pretty crapy one, since the user only knows (and is interested in) Lot Numbers not the ID it was assigned during data insertion.
Then I tried to put two php functions into one page, the first that fetches data from Mysql into a PHP dropdown menu, telling it to show every ID that matches the search criteria (lotto):
<?php if (isset($_POST['submitted'])){
include ('../mysql_connect.php'); // connessione al database
$category = 'lotto';
$criteria = $_POST['criteria'];
$query = "SELECT * FROM mappa WHERE $category = '$criteria'";
$result = mysqli_query($dbcon, $query) or die('Impossibile reperire i dati');
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$idTab = $row['id'];
echo "<option>
$idTab </option>";
}
} // FINE if ?>
</select>
Fetching data from MySQL into the dropdown worked just fine, but I got stucked in the syntax trying to use this dropdown as a search criteria for my first function.
Every help would really be appreciated! Thank you in advance for your answers.

You said that lotto is unique. So how come you are able to insert multiple rows with the same lotto?
Remove the unique constraint from the lotto column.
Try the following:
$query = select lotto, group_concat(id) as ID numbers from mappa where lotto = 'user search number' group by lotto;
$result = $conn->query($query);
$rows = $result->num_rows;
$result->data_seek(0); //move to first row (which is the only one)
$row = $result->fetch_array(MYSQLI_NUM); //fetch array
$id_numbers_string = $row[1]; //store the values of the row's second column (which is number 1)
$id_numbers_separated_array = explode(",", $id_numbers_string); //create an array with the values in the string
for($i = 0; $i < count($id_numbers_separated_array); $i++){ //loop through created array
echo "ID: " . $id_numbers_separated_array[$i];
echo "<br>";
}
Also try to run the query in your database management system to see the results.

Related

My PHP Code is Not Updating Values In Database

I have tried to write a code that update category in the database using admin panel but whenever i try to do that it won't work and i don't get any errors to look into it, please help guys; thanks a lot
PHP Code:
<?php
if (isset($_GET['edit'])) {
$edit_id = $_GET['edit'];
$query = "SELECT * FROM categories WHERE category_id = $edit_id ";
$edit_get_result = mysqli_query($connection,$query);
if (!$edit_get_result) {
die("Edit Get Result Query FAILED");
}
while ($category_name_row=mysqli_fetch_assoc($edit_get_result)) {
$category_name = $category_name_row['category_name'];
}
?>
<center>
<form action="category.php" method="POST">
<div class="form-group">
<label for="update_category">Update Category</label>
<input type="text" class="form-control" id="update_category" value="<?php if(isset($category_name)){echo $category_name; } ?>" name="update_category" aria-describedby="emailHelp" placeholder="Enter Category Name">
</div>
<button type="submit" name="update_category_submit" class="btn btn-primary">Update</button>
</form>
</center>
<?php
if (isset($_POST['update_category_submit'])) {
$category_name = $_POST['update_category'];
$query = "UPDATE categories SET category_name = '$category_name' WHERE category_id = $edit_id ";
$final_update_query_result = mysqli_query($connection,$query);
if (!$final_update_query_result) {
die("Final Update Query Result FAILED");
}
}
}
?>
Please check below code. You need to pass edit_id in your form POST. I have put it in a hidden input and set it's value according to the GET parameter from top of your php part.
<?php
if (isset($_GET['edit'])) {
$edit_id = mysqli_real_escape_string($connection,$_GET['edit']);
$query = "SELECT * FROM categories WHERE category_id = '$edit_id' ";
$result = mysqli_query($connection,$query);
if(!$result) {
die("Edit Get Result Query FAILED");
}
while ($row=mysqli_fetch_assoc($result)) {
$category_name = $row['category_name'];
}
?>
<center>
<form action="category.php" method="POST">
<div class="form-group">
<label for="update_category">Update Category</label>
<input type="text" class="form-control" id="update_category" value="<?php if(isset($category_name)){echo $category_name; } ?>" name="update_category" aria-describedby="emailHelp" placeholder="Enter Category Name">
</div>
<input type="hidden" name="edit_id" value="<?php if(isset($edit_id)) echo $edit_id;?>">
<button type="submit" name="update_category_submit" class="btn btn-primary">Update</button>
</form>
</center>
<?php
if (isset($_POST['update_category_submit']) && isset($_POST['edit_id'])) {
$category_name = mysqli_real_escape_string($connection,$_POST['update_category']);
$edit_id = mysqli_real_escape_string($connection,$_POST['edit_id']);
$query = "UPDATE categories SET category_name = '$category_name' WHERE category_id = $edit_id ";
$result = mysqli_query($connection,$query);
if (!$result) {
die("Final Update Query Result FAILED");
}
else echo "Final Update Query Result Success";
}
?>
Hi have noticed that you have used raw inputs. try avoiding it. Also noticed your code had extra curly braces at the end.
Please try using the following code after replacing your end page section php script.
if (isset($_POST['update_category_submit'])) {
$category_name = $_POST['update_category'];
$query = "UPDATE categories SET category_name = '$category_name' WHERE category_id = $edit_id ";
$final_update_query_result = mysqli_query($connection,$query);
if (!$final_update_query_result) {
die("Final Update Query Result FAILED");
}
}
And Change your query variable to the following:
$query = "SELECT * FROM categories WHERE category_id = ".$edit_id;

Updating mysql database table with variable from php calculation

I am making an addition using php and I want to update the output to a column from my database.
This is what I have:
$api = "https://blockchain.info/ticker";
$json = file_get_contents($api);
$data = json_decode($json, TRUE);
$rate = $data["USD"]["sell"];
$symbol = $data["USD"]["symbol"];
$query = $db->query("SELECT * FROM bit_buysell WHERE status='1' ORDER BY id");
if($query->num_rows>0) {
while($row = $query->fetch_assoc()) {
echo ''.$row[name].' '.$row[currency].''.$row[price].'';
}
}
echo "<br><center> <b>1 BTC = " . $rate . $symbol . "</b></center></div>";
?></li>
<?php
$query = $db->query("SELECT * FROM bit_buysell WHERE id='1' ORDER BY id");
if($query->num_rows>0) {
while($row = $query->fetch_assoc()) {
echo ''.$row[prce].'';
$first_number = $rate ;
$second_number = $row[price];
$sum_totalbuy = $first_number * $second_number;
print ($sum_totalbuy);
}
}
I have been able to successfully add the the bitcoin price ticker and my custom value which returns the result I want in the print ($sum_totalbuy);
I want to therefore update my database by changing a table which automatically reference the $sum_totalbuy
Here is what i have done -
mysql_query("UPDATE bit_rates SET id='38' WHERE rate_from='$sum_totalsell'");
it didn't work and I have this too which I don't know how to go about it
Here is the code that manually update it via my dashboard, because I have to enter rate from and rate to:
<div class="card-body">
<form action="" method="POST">
<div class="form-group">
<label>List with exchange rates</label>
<select class="form-control" name="rid">
<?php
$query = $db->query("SELECT * FROM bit_rates ORDER BY id");
if($query->num_rows>0) {
while($row = $query->fetch_assoc()) {
echo '<option value="'.$row[id].'">'.gatewayinfo($row[gateway_from],"name").' '.gatewayinfo($row[gateway_from],"currency").' ('.$row[rate_from].' '.gatewayinfo($row[gateway_from],"currency").') = '.gatewayinfo($row[gateway_to],"name").' '.gatewayinfo($row[gateway_to],"currency").' ('.$row[rate_to].' '.gatewayinfo($row[gateway_to],"currency").')</option>';
}
} else {
echo '<option>No gateways</option>';
}
?>
</select>
</div>
<div class="form-group">
<label>New exchange rate</label>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">Rate from</span>
<input type="text" class="form-control" name="rate_from" placeholder="1" aria-describedby="basic-addon1">
<span class="input-group-addon" id="basic-addon1">= Rate to</span>
<input type="text" class="form-control" name="rate_to" placeholder="0.95" aria-describedby="basic-addon1">
</div>
</div>
<button type="submit" class="btn btn-primary" name="btn_update_rate"><i class="fa fa-check"></i> Update</button>
</form>
Please help me fix it.$sum_totalbuy
I need to store the print ($sum_totalbuy); to be updated in rate_from I will handle rate_to $sum_totalbuy
i have finally gotten it to work and this is what i did.
I had to do a total reconnect to my database then did the query update.
<?php
$server = "host";
$user = "user";
$pass = "pass";
$db = "db";
// Create connection
$conn = mysqli_connect($server, $user, $pass, $db);
// Check connection
if (!$conn) {
die("Could not connect: " . mysqli_connect_error());
}
$sql = "UPDATE bit_rates SET rate_from='$sum_totalsell' WHERE id=38";
if (mysqli_query($conn, $sql)) {
echo "Sell Rate Update successful.";
}
$sql = "UPDATE bit_rates SET rate_to='$sum_totalbuy' WHERE id=37";
if (mysqli_query($conn, $sql)) {
echo "Buy Rate Update successful.";
}
else {
echo "Could not update: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
That directly updates the table in my sql
Thanks everyone for the time
i found the help here https://www.bitdegree.org/learn/mysql-update-syntax/

PHP DATA Fetch Issue

I am very new to PHP and HTML. I am trying to fetch the row value from input form data, but i am unable to fetch the data.
Below is my code.
HTML:
<form id="main" action="test.php" method="post" enctype="multipart/form-data" >
<div class="row">
<div class="col-md-12">
<label for="model" style="font-size: 15px"> Model </label><br>
<input type="text" id="tags" name="model" placeholder="Type Your Model Number" >
</div>
</div>
<div class="row">
<div class="col-md-12">
<button type="submit" id="button" name="submit1" />SUBMIT</button>
</div>
</div>
</form>
</html>
PHP CODE:
<?php
if(isset($_POST['submit']))
{
// id to search
$model = $_POST['model'];
// connect to mysql
$connect = mysqli_connect("localhost", "root", "","test");
// mysql search query
$query = "SELECT `offer`, `amount` FROM `offer`";
$result = mysqli_query($connect, $query);
// if id exist
// show data in inputs
if(mysqli_num_rows($result) > 0)
{
while ($row = mysqli_fetch_array($result))
{
$offer = $row['offer'];
$amount = $row['amount'];
}}
if($model){
echo "
<form method='post' action=''>
<div class='col-md-5'>
$offer
</div>
<div class='col-md-5'>
INR $amount/-
</div>
</div></form>";
else {
$offer = "";
$amount = "";
$offer2 = "";
$amount2 = "";
}
mysqli_free_result($result);
mysqli_close($connect);}
else{
$offer = "";
$amount = "";
$offer2 = "";
$amount2 = "";
}
?>
Also, please note that the model is alphanumeric. Offer would be Headset and amount would be 100. I request to help me on this.
First of all we don't know what your error is and second you haven't included all your code. However, for PHP use following code
<?php
$mysqli = new mysqli("localhost", "root", "", "test") or die($mysqli->error);
$select = $mysqli->query("SELECT * from offer") or die($mysqli->error);
if($select->num_rows){
while($row = $select->fetch_array(MYSQLI_ASSOC)){
$amount = $row['amount'];
$offer= $row['offer'];
}
}
?>
You have used input and button but i don't see any form tags in HTML
You have to pass the $model in your query and do that to show the results:
echo "<form method='post' action=''>";
while ($row = mysqli_fetch_array($result))
{
echo " <div class='col-md-5'>
".$row['offer']."
</div>
<div class='col-md-5'>
INR ".$row['amount']."-
</div> ";
}
echo "</form>";

How to get values of dynamically generated textarea inputs with php

I'm having a challenge with a mini project I'm working on and have googled for a solution for hours without a headway.
I have a column in my database table whose contents are generated by exploding a previous form inputs(separated by comma in the table). Now I need to get inputs (from users) for these values using textarea in a form. These inputs will be in arrays depending on the number of contents fetched from the db in the first place and then stored in another column in my table. The issue here is that each time I submit the form I get an undefined index notice for the name of the values in the textarea field, which is test-col [].
please see my code below:
<?php
$conn = mysqli_connect('localhost', 'root', '', 'myDb');
$users_id = mysqli_real_escape_string($conn, $_GET['id']);
$res = mysqli_query($conn, "SELECT tests FROM bal WHERE users_id = '$users_id'");
if ($res){
while ($row = mysqli_fetch_array($res)){
$tests = explode(',', $row['tests']);
foreach($tests as $test){
if ($test ==""){
continue;
}
echo '<div class="test-res" style="margin-top:10px;">
<form action="" method="post" role="form" class="form-horizontal">
<div class="form-group">
<label for= "test-col" class="form-label col-md-2">'.$test.' test</label>
<div class="col-md-10">
<textarea class="form-control" rows="3" name="test-col[]" placeholder="Test result"> </textarea>
</div>
</div>
</form>
</div>';
'<br /> <br />';
}
}
}
echo '<form action="" method="post">
<button type="submit" class="btn btn-success col-md-offset-5" name="sub-res">Send Result</button>
</form>';
?>
//to insert textarea values in db
<?php
if(isset($_POST['sub-res'])){
$conn = mysqli_connect('localhost', 'root', '', 'myDb');
foreach ($_POST ['test-col'] as $values){
$test_results = implode("<br>", $values);
}
$ins = mysqli_query($conn, "INSERT INTO bal (results) VALUES
('$test_results') WHERE users_id = '$users_id'");
if (!$ins){
die(mysqli_error());
}
else{
echo '<div class="alert alert-success">Successfully sent</div>';
}
}
?>
You have two forms - one in your while/foreach statement, and then one below. If you're submitting the second form, it won't contain values from the first.
Wrap the while in the form instead;
<form action="" method="post">
<?php
$conn = mysqli_connect('localhost', 'root', '', 'myDb');
$users_id = mysqli_real_escape_string($conn, $_GET['id']);
$res = mysqli_query($conn, "SELECT tests FROM bal WHERE users_id =
'$users_id'");
if ($res){
while ($row = mysqli_fetch_array($res)){
$tests = explode(',', $row['tests']);
foreach($tests as $test){
if ($test =="") {
continue;
}
echo '<div class="test-res" style="margin-top:10px;"><div class="form-group">
<label for= "test-col" class="form-label col-md-2">'.$test.' test</label><div class="col-md-10"><textarea class="form-control" rows="3" name="test-col[]" placeholder="Test result"> </textarea></div></div></div>';
'<br /> <br />' ;
}
}
}
?>
<button type="submit" class="btn btn-success col-md-offset-5" name="sub-res">Send Result</button>
</form>

Updating multiple fields

I have multiple fields on admin panel user can add field and delete the fields as well while adding it I placed simple insert query with foreach loop but it is difficult to understand the concept for updating that fields if user deletes a field or updates it is not working if I delete 1 field and update it it deletes 2 or more then 2 fields and when I try to update it is not updating well update issue is due i would be making some mistake with query. But main thing is about logic which I am unable to build it properly need help.
Update query
$video_link = $_POST['video_link'];
$old_links = count($video_link);
if(isset($_POST['video_id'])) {
$video_id = $_POST['video_id'];
$total_id = count($video_id);
} else {
$video_id = '';
}
$video_links = mysqli_query($connect, "SELECT * FROM video_slides WHERE model_id = '$model_id'");
$total_links = mysqli_num_rows($video_links);
$video_link = sizeof($video_link) - 1;
if($total_links >= 1) {
for($i = 0; $i<=$video_link; $i++) {
if(empty($video_id[$i])) {
mysqli_query($connect, "INSERT INTO `video_slides`(`embeded_link``, `model_id`) VALUES ('$video_link[$i]', '$model_id')");
}
$query2 = mysqli_query($connect, "UPDATE `video_slides` SET `embeded_link`='$video_link[$i]' WHERE id='$video_id[$i]'");
if($video_link < $total_links) {
$new_total = $total_links-sizeof($video_link);
for($j = 0; $j<=$new_total; $j++) {
mysqli_query($connect, "DELETE FROM video_slides WHERE id='$video_id[$j]'");
}
}
}
} else {
for($i = 0; $i<=$video_link; $i++) {
if(empty($video_id[$i])) {
mysqli_query($connect, "INSERT INTO `video_slides`(`embeded_link``, `model_id`) VALUES ('$video_link[$i]', '$model_id')");
}
}
}
And here is my form fields
<div class="form-group">
<label>Video Slides <input type="button" class="add_field_button btn blue" value="Add Field" /></label>
<div class="input_fields_wrap">
<?php
$sql3 = mysqli_query($connection, "SELECT * FROM video_slides WHERE model_id = '".$data['id']."'");
if(mysqli_num_rows($sql3) == 0) {
?>
<div class="new">
<input type="text" id="video_link" size="20" name="video_link[]" placeholder="Embeded Video Link" class="form-control" />
</div>
<?php
} else {
while($video = mysqli_fetch_assoc($sql3)) {
?>
<div class="new">
<input type="text" id="video_link" size="20" name="video_link[]" placeholder="Embeded Video Link" class="form-control" value="<?php echo $video['embeded_link']; ?>" />
<input type="hidden" value="<?php echo $video['id']; ?>" name="video_id[]" />
<a class="remove_field"><i class="fa fa-times"></i></a>
</div>
<?php } } ?>
</div>
</div>
As per my understanding you need only these thing why you making complex coding
$video_link = $_POST['video_link'];
//First Remove All ID
mysqli_query($connect, "DELETE FROM video_slides WHERE model_id='$model_id'");
//Then After insert updated data
foreach($video_link as $key=>$val){
mysqli_query($connect, "INSERT INTO `video_slides`(`embeded_link`, `model_id`) VALUES ('$val', '$model_id')");
}
you should try to outsource your db connections in a separate class - this will lead to better readable code. An ORM like Doctrine can definitely help you to better understand your own code.

Categories