Updating value into database - php

I have problem in updating the value into my database. The problem here is that the when i am updating the data for all rows, the data from last row will be updated into the first row. Other rows will not be updated including the last row.
Below is my code for updating...
$sql = "SELECT * FROM product where username = '$username'";
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
$rows = mysqli_fetch_array($result);
$id = $rows['pro_id'];
$boxid = $rows['box_id'];
$name = $_POST['pro_name'];
$quan = $_POST['pro_quan'];
$sold = $_POST['pro_sold'];
for ($i = 0; $i < count($_POST['pro_name']); $i++)
{
$sql = "UPDATE product
SET pro_name = '" . $name[$i] . "',
pro_quan = " . $quan[$i] . ",
pro_sold = " . $sold[$i] . "
WHERE pro_id = " . $id . "
AND box_id = '" . $boxid . "' ";
$results=mysqli_query($con, $sql);
}
So, i have no ideas what have gone wrong. Thanks for helping

You need to place the result in a loop.
Something like that:
$sql = "SELECT * FROM product where username = '$username'";
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
while ($rows = mysqli_fetch_array($result))
{
$id = $rows['pro_id'];
$boxid = $rows['box_id'];
$name = $_POST['pro_name'];
$quan = $_POST['pro_quan'];
$sold = $_POST['pro_sold'];
for ($i = 0; $i < count($_POST['pro_name']); $i++)
{
$sql = "UPDATE product
SET pro_name = '" . $name[$i] . "',
pro_quan = " . $quan[$i] . ",
pro_sold = " . $sold[$i] . "
WHERE pro_id = " . $id . "
AND box_id = '" . $boxid . "' ";
$results = mysqli_query($con, $sql);
}
}

Related

How to update item in sql if a variable isn't empty?

I'm getting variable from parser.
If variable $desc is empty - my request just stops, but I need just pass it.
It's my part of code.
$desc = $description->plaintext;
if(!empty($desc)) {
$query = "UPDATE snowcore_parser_products SET description = 'blabla' WHERE remote_id = '" . $dataId . "';";
} else {
$query = "UPDATE snowcore_parser_products SET description = 'EMPTY' WHERE remote_id = '" . $dataId . "';";
}
$sql = mysqli_query($db, $query);
But if(!empty($desc)) doesn't work
Try this
$desc = $description->plaintext;
if(count($desc)>0) {
$query = "UPDATE snowcore_parser_products SET description = 'blabla' WHERE remote_id = '" . $dataId . "';";
} else {
$query = "UPDATE snowcore_parser_products SET description = 'EMPTY' WHERE remote_id = '" . $dataId . "';";
}
$sql = mysqli_query($db, $query);
Are you sure $desc is empty, mind you a space or newline character will not make it empty. Check the value by debugging or by var_dump(). If there is space or newline you can use trim().
$desc = trim($description->plaintext);
if(!empty($desc)) {
$query = "UPDATE snowcore_parser_products SET description = 'blabla' WHERE remote_id = '" . $dataId . "';";
} else {
$query = "UPDATE snowcore_parser_products SET description = 'EMPTY' WHERE remote_id = '" . $dataId . "';";
}
$sql = mysqli_query($db, $query);

json_decode, trying to access array element

$objetos = json_decode($_POST['objetos']);
$query1 = "DELETE FROM `usuarioObjeto` WHERE idusuario=" . $id . "";
$result1 = mysqli_query($conn, $query1) or die('Consulta fallida: ' . mysqli_error());
$size = count($objetos); //this works
//this do not insert into the BD
for ($k = 0; $k < $size; $k++) {
$ido = intval($objetos[$k]['id']);
$cantidad = intval($objetos[$k]['cantidad']);
$query2 = "INSERT INTO `usuarioObjeto`( `idUsuario`, `idObjeto`, `cantidad`) VALUES (" . $id . "," . $ido . "," . $cantidad . ")";
$result2 = mysqli_query($conn, $query2) or die('Consulta fallida: ' . mysqli_error());
}
thanks
and i have tried to access to one property like this but nothing
$ido = intval($objetos[0]['id']);
json_decode($_POST['objetos']); replece to json_decode($_POST['objetos'],true);
By adding true as a second parameter, it will convert your json to array
More information: json_decode
Use this code :
$objetos = json_decode($_POST['objetos'],true);

SQL Edits first option only

This is the code from our handle page we are trying to edit our database in phpmyadmin but can seem to only edit our first entry even though we clicked on other entries' edit button
require 'dbfunction.php';
$con = getDbConnect();
$crew_id = $_POST["crew_id"];
$CrewName = $_POST["CrewName"];
$CrewRank = $_POST["CrewRank"];
$StartDate = $_POST["StartDate"];
$EndDate = $_POST["EndDate"];
$PayrollNo = $_POST["PayrollNo"];
$EmployeeNo = $_POST["EmployeeNo"];
$WatchKeeping = $_POST["WatchKeeping"];
$Active = $_POST["Active"];
//$Delete = $_POST["Delete"];
if (!mysqli_connect_errno($con)) {
$queryStr = "SELECT crew_id " .
"FROM crewlist";
}
$result = mysqli_query($con, $queryStr);
while ($row = mysqli_fetch_array($result)) {
if (!mysqli_connect_errno($con)) {
$sqlQueryStr = "UPDATE crewlist SET crew_name = '$CrewName', crew_rank = '$CrewRank', start_date = '$StartDate' "
. ", end_date = '$EndDate', payroll_no = '$PayrollNo'"
. ", employee_no = '$EmployeeNo', watchkeeping = '$WatchKeeping', active = '$Active' WHERE crew_id = " . $row['crew_id'];
mysqli_query($con, $sqlQueryStr);
mysqli_close($con);
} else {
break;
}
header('Location: crewlisting.php');
}
?>
This code only edits the first entry of our database and the rest remains stagnant. This is the code from our edit page
<?php
if (!mysqli_connect_errno($con)) {
$queryStr = "SELECT * " .
"FROM crewlist";
}
$result = mysqli_query($con, $queryStr);
while ($row = mysqli_fetch_array($result)) {
echo "<tr>.<th>" . $row["crew_name"] . "<br></br>" . "</th>";
echo "<th>" . $row["crew_rank"] . "</th>";
echo "<th>" . $row["start_date"] . "</th>";
echo "<th>" . $row["end_date"] . "</th>";
echo "<th>" . $row["watchkeeping"] . "</th>";
echo "<th>" . $row["active"] . "</th>";
//echo "<td><form action=\"editcrew.php\" method=\"post\"><a href='editcrew.php?del={$row['crew_id']}'>edit</a></form></td>";
echo "<td>Edit";
echo "<td><form action=\"delete.php\" method=\"post\"><a href='crewlisting.php?del={$row['crew_id']}'>delete</a></form></td>";
}
?>
You are closing your mysqli connection in the first iteration of your loop. Move the mysqli_close($con); behind the loop.
Edit: And you also redirect to crewlist.php in the loop. If you reformat your indentation of your code, this will get obvious.
Remove mysqli_close($con) from loop:
while ($row = mysqli_fetch_array($result)) {
$sqlQueryStr = "UPDATE crewlist SET crew_name = '$CrewName', crew_rank = '$CrewRank', start_date = '$StartDate' "
. ", end_date = '$EndDate', payroll_no = '$PayrollNo'"
. ", employee_no = '$EmployeeNo', watchkeeping = '$WatchKeeping', active = '$Active' WHERE crew_id = " . $row['crew_id'];
mysqli_query($con, $sqlQueryStr);
}
header('Location: crewlisting.php');

PHP Dynamic Count Function

I am trying to make ONE dynamic function for count in mysql:
functions.php:
function countEntries($table, $where = '', $what = '')
{
if (!empty($where) && isset($what)) {
$q = "SELECT COUNT(*) FROM " . $table . " WHERE " . $where . " = '" . $what . "' LIMIT 1";
} else{
$q = "SELECT COUNT(*) FROM " . $table . " LIMIT 1";
}
$record = query($q);
$total = fetchrow($record);
return $total[0];
}
HTML Code:
<?php echo countEntries("news", "category", "1"); ?>
<?php echo countEntries("post", "type", "Sports"); ?>
But still got blank page without any error!!!
You can try this out.
function countEntries($table, $where = '', $what = '')
{
if (!empty($where) && isset($what)) {
$q = "SELECT COUNT(*) AS count FROM " . $table . " WHERE " . $where . " = '" . $what . "' LIMIT 1";
} else{
$q = "SELECT COUNT(*) AS count FROM " . $table . " LIMIT 1";
}
$record = query($q);
$total = fetchrow($record);
return $total['count'];
}
Here you give an alias to the count(*) and use that to access the returned result as $total['count'].
Hope it helps.
First things you forgot to close else past,second just add this line "ini_set("display_errors", 1);" at the top of your php.this will shows the error in your php.
Your code:
function countEntries($table, $where = '', $what = '')
{
if (!empty($where) && isset($what)) {
$q = "SELECT COUNT(*) FROM " . $table . " WHERE " . $where . " = '" . $what . "' LIMIT 1";
} else
$q = "SELECT COUNT(*) FROM " . $table . " LIMIT 1";
}
$record = query($q);
$total = fetchrow($record);
return $total[0];
}
my code:
function countEntries($table, $where = '', $what = '')
{
if (!empty($where) && isset($what)) {
$q = "SELECT COUNT(*) AS count FROM " . $table . " WHERE " . $where . " = '" . $what . "' LIMIT 1";
} else{
$q = "SELECT COUNT(*) AS count FROM " . $table . " LIMIT 1";
}
$record = query($q);
$total = fetchrow($record);
return $total['count'];
}
Thanks guys, Its working well now:
function countEntries($table, $where, $what)
{
if (!empty($where) && isset($what)) {
$q = "SELECT COUNT(*) FROM " . $table . " WHERE " . $where . " = '" . $what . "' LIMIT 1";
} else
$q = "SELECT COUNT(*) FROM " . $table . " LIMIT 1";
$record = mysql_query($q);
$total = mysql_fetch_array($record);
return $total[0];
}
echo countEntries('news', "type", "sport");

Get summed value from specific rows

I have this:
$result = mysqli_query($mysqli, "SELECT balance FROM " . MYSQLBTCTABLE . " WHERE address='" . $_POST['address'] . "' LIMIT 1");
while($row = mysqli_fetch_assoc($result)) {
$balance = $row['balance'];
echo "<font style='font-weight:bold;'>Your current balance is: </font><br/>";
printf("%0.8f", ($balance / 100000000));
but it gets only the last value I need to find all balances from that address and sum them in total for the $balance.
Remove limit 1 and do the sum
$result = mysqli_query($mysqli, "SELECT balance FROM " . MYSQLBTCTABLE . " WHERE
address='" . $_POST['address'] . "' ");
$balance = 0;
while($row = mysqli_fetch_assoc($result)) {
$balance += $row['balance'];
echo "<font style='font-weight:bold;'>Your current balance is: </font><br/>";
printf("%0.8f", ($balance / 100000000));
Use
$balance += $row['balance'];
Use agregation:
$result = mysqli_query($mysqli, "SELECT sum(balance) FROM " . MYSQLBTCTABLE . " WHERE address='" . $_POST['address'] . "' GROUP BY address");
Remove the LIMIT out of the query and add SUM
$result = mysqli_query($mysqli, "SELECT SUM(balance) as totalBalance FROM " . MYSQLBTCTABLE . " WHERE address='" . $_POST['address'] . "'");
$row = mysqli_fetch_assoc($result);
$balance = $row['totalBalance'];
echo "<font style='font-weight:bold;'>Your current balance is: </font><br/>";
printf("%0.8f", ($balance / 100000000));
First of all,instead :
$balance = $row['balance'];
use:
$balance += $row['balance'];
Furthermore, get rid of the "LIMIT 1" constraint

Categories