Updating mysql database table with variable from php calculation - php

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/

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;

how to display the mobile no in mobile no label searching by employee id in html using php and mysql

I want to display the mobile number in mobileNo label but when I enter the employee id for search this code displays no result.
I want to display data using the while loop in my html form
search.php
<?php
$output = NULL;
$mysqli = mysqli_connect("localhost","root","","db") or die ("Error in connection");
if(isset($_POST['search']))
{
$search = $mysqli->real_escape_string(isset($_POST['search']));
$resultSet = $mysqli->query("SELECT * FROM emp WHERE emp_id = '$search'");
if($resultSet->num_rows > 0)
{
while($rows = mysqli_fetch_row($resultSet))
{
$mobileNo = $rows['emp_mob_no'];
$output = "Mobile no: $mobileNo";
}
}
{
$output = "No result";
}
}
?>
display.php
<html>
<head>
</head>
<body>
<form action="search.php" method="post">
<ul>
<li>
<label for="employeeId">Employee Id</label>
<input type="text" name="employeeId" placeholder="Employee Id" />
<input type="submit" value="search" name="search"/>
</li>
<li>
<label for="mobileNo">Mobile No.</label>
<?php echo $output;?>
</li>
</form>
</body>
</html>
1st : you missed else That's why $output variable alwasy overwrite by No result .
2nd : $search = $mysqli->real_escape_string(isset($_POST['search'])); this line wrong isset will return boolean value your escaping for boolean value .
3rd : Try to use prepared statement to avoid sql injection .
PHP:
<?php
$output = NULL;
$mysqli = mysqli_connect("localhost","root","","db") or die ("Error in connection");
if(isset($_POST['search']))
{
$search=$_POST['search'];
$stmt = $conn->prepare("SELECT * FROM emp WHERE emp_id = ?");
$stmt->bind_param('i',$_POST['search']);
$stmt->execute();
$get_result = $stmt->get_result();
if($get_result->num_rows > 0)
{
while($rows = $get_result->fetch_assoc())
{
$mobileNo = $rows['emp_mob_no'];
$output = "Mobile no: $mobileNo";
}
}else //here else missed .
{
$output = "No result";
}
}
?>
<?php
$output = NULL;
$mysqli = mysqli_connect("localhost","root","","db") or die ("Error in connection");
if(isset($_POST['search']))
{
$search = $mysqli->real_escape_string($_POST['search']);
$resultSet = $mysqli->query("SELECT * FROM emp WHERE emp_id = '$search'");
if($resultSet->num_rows > 0)
{
while($rows = mysqli_fetch_assoc($resultSet))
{
$mobileNo = $rows['emp_mob_no'];
$output = "Mobile no: $mobileNo";
}
}
else
{
$output = "No result";
}
}
?>

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>";

Insert, Update, Search in MySql database using 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.

Creating a search function

I have multiple fields in my search form and my query works for individual fields. what i'm trying to achieve is
1- query should work if search is based on 1 field
2- query should work if search is based on multiple fields entry
my form
<form class="sidebar-search jumbro-search container list-inline center-block" method="get" action="search.php">
<div class="form-group col-md-2">
<input list="location" name="location" class="form-control" placeholder="Location">
<datalist id="location">
<?php
$loc="select * from locations";
$results=mysqli_query($dbc,$loc);
while($row_loc=mysqli_fetch_array($results)){
echo '<option value='.$row_loc['region'].'>'.$row_loc['region'].'</option>';
}
?>
</datalist>
</div>
<div class="form-group col-md-2">
<select class="form-control" name="category">
<option selected>Category</option>
<?php
$cat="select * from property_type order by type_name asc";
$results=mysqli_query($dbc,$cat);
while($row_cat=mysqli_fetch_array($results)){
echo '<option value='.$row_cat['type_name'].'>'.$row_cat['type_name'].'</option>';
}
?>
</select>
</div>
<div class="form-group col-md-2">
<select class="form-control" name="status">
<option selected>Status</option>
<?php
$status="select * from property_status order by status_name asc";
$results=mysqli_query($dbc,$status);
while($row_status=mysqli_fetch_array($results)){
echo '<option value='.$row_status['status_name'].'>'.$row_status['status_name'].'</option>';
}
?>
</select>
</div>
<div class="form-group col-md-2">
<input type="text" name="price-max" value="999999999999" class="form-control" placeholder="Max Price">
</div>
<div class="form-group col-md-2">
<button class="btn btn-primary form-control">Search</button>
</div>
and my php script looks like this
// getting user data from search form
$location=$_GET['location'];
$category=$_GET['category'];
$status=$_GET['status'];
//scripts
if($location!="location" && $category!="category" && $status!="status"){
$query="select * from properties where `property_type` like '%$category%' && `location` like '%$location%' && `status` like '%$status%' ";
}
$query="select * from properties where `property_type` like '%$category%' or `location` like '%$location%' or `status` like '%$status%'";
$result=mysqli_query($dbc,$query);
if(mysqli_query($dbc,$query)) {
$num_rows=mysqli_num_rows($result);
} else {
echo 'Query failed';
}
$num_rows=mysqli_num_rows($result);
if($num_rows!=0){
echo '<h3 class="page-header text-center">'.$num_rows.' Match Found</h3>';
while ($row=mysqli_fetch_array($result)) {
<?php
}//end while
}else{
echo '<h3 class="page-header text-center">No Match Found, try adjusting your search criteria.</h3>';
include 'functions/latest-sc.php';
}
Well, okay, I have several ideas about what you should change in your code.
I strongly recommend you to separate representative logic (html and echoing variables) from functionality like defining variables and handling database queries. It will help you a lot in future.
You can use default option in your selects with empty value
<option value="">Select none</option>
It will simplify your code in checks:
Instead of:
if($location!="location" && $category!="category" && $status!="status")
Can use:
if($location && $category && $status)
Read about escaping
On your main question - you can create query by concatenation. I give you example and you can replace it with 'OR' or 'AND' for your needs:
$sql = 'SELECT * FROM properties WHERE ';
$scopes = [];
foreach([$location,$category,$status] as $column => $condition) {
if ($condition) {
$scopes[] = $column.' LIKE \'%.$condition.'%\'';
}
}
$scopes = implode(' AND ',$scopes);
$sql .= $scopes.';';
// ...do what you need
There is a lot more advices for coding but maybe you just present it like dead-simple example, so I skip it.
OK I think what you are asking is a SELECT based on multiple columns in a table. Below is a script from my application that selects records from a table that checks for a hometeam and an away team:-
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "localdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT hometeam FROM stats WHERE hometeam = 'Man City' AND awayteam = 'Sunderland'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['hometeam'];
}
} else {
echo "0 results";
}
$conn->close();
?>
This should work:
$data = [
'property_type' => 'category_value', //$_GET['location']
'category' => 'location_value', //$_GET['category']
'status' => 'status_value' //$_GET['status']
];
$select = "";
$params = 0;
foreach($data as $k => $v){
if($params > 0){
$select .= " or ";
}
//add some better conditions
if(strlen($v) > 0){
$select .= "`$k` LIKE %$v%";
$params++;
}
}
$query = "select * from properties where " . $select;
print_r($query);

Categories