How to get MySQL Update to work - mysql

I'm trying to get the mySQL update to work below and there's no console error but it doesn't reflect any changes I have made to the database.
Please let me know if i miss out anything.
Appreciate it very much.
table 1: nmc_cd
table 2: nmc_category
table 3: nmc_publisher
In this update php, it gets the values from the previous php and update the table.
<?php
header('Content-type: text/html; charset=iso-8859-1');
include 'database_conn.php'; // make db connection
$pCDTitle = filter_has_var(INPUT_GET, 'CDTitle') ? $_GET['CDTitle']: null; // store all parameter in variable
$pCDPubName = filter_has_var(INPUT_GET, 'CDPub') ? $_GET['CDPub']: null;
$pCDYear = filter_has_var(INPUT_GET, 'CDYear') ? $_GET['CDYear']: null;
$pCDCategory = filter_has_var(INPUT_GET, 'CDCat') ? $_GET['CDCat']: null;
$pCDPrice = filter_has_var(INPUT_GET, 'CDPrice') ? $_GET['CDPrice']: null;
$pCDID = filter_has_var(INPUT_GET, 'CDID') ? $_GET['CDID']: null;
$pCDPubID = filter_has_var(INPUT_GET, 'pubID') ? $_GET['pubID']: null;
$sql = "UPDATE nmc_cd "
. "SET nmc_cd.CDTitle='$pCDTitle',nmc_cd.CDYear='$pCDYear',nmc_cd.CDPrice='$pCDPrice',nmc_cd.catID='$pCDCategory',nmc_cd.pubID='$pCDPubName'"
. "WHERE nmc_cd.CDID='$pCDID'";
if ($conn->query($sql) === TRUE) {
echo "<b><font face='verdana' font sise='3' color='red'>Record updated successfully</font></b>";
$sql = "SELECT * FROM nmc_cd "
. "JOIN nmc_category ON (nmc_cd.catID = nmc_category.catID)"
. "JOIN nmc_publisher ON (nmc_cd.pubID = nmc_publisher.pubID)"
. "WHERE nmc_cd.CDID = '$pCDID'"; //Query Database
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$CDID = $row['CDID'];
$CDTitle = $row['CDTitle'];
$CDYear = $row['CDYear'];
$CDPrice = $row['CDPrice'];
$catDesc = $row['CDCat'];
$pubName = $row['CDPub'];
$location = $row['location'];
echo "<table>";
echo "<tr><th>Title</th><th>Year</th><th>Price</th><th>Catergory</th><th>Publisher</th><th>Location</th></tr>";
echo "<tr><td>".$row["CDTitle"]."</td><td> ".$row["CDYear"]."</td><td> ".$row["CDPrice"]."</td><td> ".$row["CatCD"]."</td><td> ".$row["CatPub"]."</td><td> ".$row["location"]."</td></tr>"; //Display Data Table Data
echo "</table";
mysqli_close($conn);
} else {
echo "<b><font face='verdana' color='red'>Error updating record!!!</font></b>" . $conn->error;
}
?>

Related

How to Join/Combine two table when export Mysql data to Excel Download?

I Maintain 4 tables.
Table 1(table name: products)-> pro_id, pro_model, price
Table 2(table name: pro_description)-> id, pro_id, pro_name, pro_desp
Table 3(table name: pro_to_category)-> id, pro_id, cat_id
Table 4(table name: category)-> cat_id, cat_desp
Now I wants to download the fields, when I export mysql data to excel
download, pro_id, pro_name, pro_desp, price, pro_model, category
(notes: category needs the cat_desp, no need cat_id)
Thanks for advance. help me to solve. :(
<?php
/*******EDIT LINES 3-8*******/
$DB_Server = "localhost"; //MySQL Server
$DB_Username = "username"; //MySQL Username
$DB_Password = "password"; //MySQL Password
$DB_DBName = "databasename"; //MySQL Database Name
$DB_TBLName = "tablename"; //MySQL Table Name
$filename = "excelfilename"; //File Name
/*******YOU DO NOT NEED TO EDIT ANYTHING BELOW THIS LINE*******/
//create MySQL connection
$sql = "Select * from $DB_TBLName";
$Connect = #mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" . mysql_errno());
//select database
$Db = #mysql_select_db($DB_DBName, $Connect) or die("Couldn't select database:<br>" . mysql_error(). "<br>" . mysql_errno());
//execute query
$result = #mysql_query($sql,$Connect) or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());
$file_ending = "xls";
//header info for browser
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");
header("Pragma: no-cache");
header("Expires: 0");
/*******Start of Formatting for Excel*******/
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
//start of printing column names as names of MySQL fields
for ($i = 0; $i < mysql_num_fields($result); $i++) {
echo mysql_field_name($result,$i) . "\t";
}
print("\n");
//end of printing column names
//start while loop to get data
while($row = mysql_fetch_row($result))
{
$schema_insert = "";
for($j=0; $j<mysql_num_fields($result);$j++)
{
if(!isset($row[$j]))
$schema_insert .= "NULL".$sep;
elseif ($row[$j] != "")
$schema_insert .= "$row[$j]".$sep;
else
$schema_insert .= "".$sep;
}
$schema_insert = str_replace($sep."$", "", $schema_insert);
$schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
print(trim($schema_insert));
print "\n";
}
?>
Try a query along these lines:
SELECT
t1.pro_id,
t2.pro_name,
t2.pro_desp,
t1.price,
t1.pro_model,
t4.cat_desp
FROM products t1
INNER JOIN pro_description t2
ON t1.pro_id = t2.pro_id
INNER JOIN pro_to_category t3
ON t1.pro_id = t3.pro_id
INNER JOIN category t4
ON t3.cat_id = t4.cat_id

Issue in Query. Not working

<?php
echo "Hello test <br>";
$userid = $_GET['userid'];
echo "your user userid is " . $userid . " &";
$salt = $_GET['salt'];
echo " your user salt is " . $salt;
// Query for finding the data from db
// Issue in query
$sql = "SELECT * FROM test.test where id=" .$userid AND "salt=".$salt;
echo "<br>" . $sql;
$result = $conn->query($sql);
if (!empty($result))
{
echo "<br>Result Found";
}
else
{
echo "<br> Invalid link !";
}
// }
?>
My Query is not working properly. If I reduce my query to id=".$userid it works properly but if I add remaining portion its not working.
The $sql line should be:
$sql = "SELECT * FROM sauberlux_com.tbl_b2cuser where id=".$userid." AND salt=".$salt;
$sql = "SELECT * FROM sauberlux_com.tbl_b2cuser where id = $userid AND salt = $salt";
Try it.
$sql = "SELECT * FROM sauberlux_com.tbl_b2cuser where id = $userid AND salt = '$salt' ";
Also you can refer here for sql injection

I want to add the following code into a table and limit amount of entries

I have the following code on a .php page and I want to display it inside a table and only show the last 10 entries
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM dispenses";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> Amount: " . $row["amount"] . " - Time Dispensed: ". $row["dispensed"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
You could store all the results in an array and subsequently display only last 10 elements of that array.
while($row = $result->fetch_assoc()) {
$results[] = $row;
}
for($i = count($results)-10; $i < count($results); $i++){
echo "<br> Amount: " . $results[$i]["amount"] . " - Time Dispensed: ". $results[$i]["dispensed"] . "<br>";
}
You can limit the number of results with LIMIT:
$sql = "SELECT * FROM dispenses LIMIT 10";
You can choose an offset as well. Check documentation for more.
p.s.: so in order to get last x entries using order by y use:
$sql = "SELECT * FROM (SELECT * FROM dispenses ".
"ORDER BY y DESC LIMIT 10) AS intermediate ORDER by y ASC";
Check this Fiddle to see how it works. I select the last three records based on id or insert date. I forgot to define an alias in the statement above. This is fixed now. Hope it helps ....

how to write code in order to update stock after we sell a product

I have written following code for my sales_invoice.php
if(isset($_POST['submit1'])){
// $cat_array = $_POST['category_name'];
// $qua_array = $_POST['quantity'];
//$mrp_array = $_POST['mrp'];
//$vat_array = $_POST['vat'];
// print_r($_POST);
if(!empty($_POST['item_name']) && is_array($_POST['item_name'])){
$name_array =$_POST['item_name'];
//print_r($name_array);
for($j=0; $j< count($name_array);$j++){
$name = mysql_real_escape_string($name_array[$j]);
//echo $name;
//$n = explode('/',$name);
$sql = "select quantity from purchase_stock where item_name = '$name'";
// echo $sql;
$res = mysql_query($sql) or die(mysql_error());
$num_rows = mysql_num_rows($res);
if($num_rows <=0){
echo "<b>not in stock</b>";
exit();
}
else
continue;
}
}
$sql = "insert into material_inv set order_date='$new_date', due_date='$new_date1', dealer='".$_POST['dealer']."', customer='".$_POST['customer']."'";
// echo $sql;
$res = mysql_query($sql) or die(mysql_error());
if($res == true){
echo "sales invoice created";
}
else
{
echo "error";
}
$myid = mysql_insert_id();
$sales_id = $myid;
//display_item();
// print_r($_POST);
if (!empty($_POST['category_name']) && !empty($_POST['item_name']) && !empty($_POST['quantity']) && !empty($_POST['mrp']) && !empty($_POST['vat']) &&
is_array($_POST['category_name']) && is_array($_POST['item_name']) && is_array($_POST['quantity']) && is_array($_POST['mrp']) && is_array($_POST['vat'])){
// echo 'start';
$name_array = $_POST['item_name'];
$cat_array = $_POST['category_name'];
$qua_array = $_POST['quantity'];
$mrp_array = $_POST['mrp'];
$vat_array = $_POST['vat'];
//print_r($mrp_array);
for ($i = 0; $i < count($name_array); $i++) {
$name = mysql_real_escape_string($name_array[$i]);
$cat = mysql_real_escape_string($cat_array[$i]);
$q = mysql_real_escape_string($qua_array[$i]);
$mrp = mysql_real_escape_string($mrp_array[$i]);
//echo $mrp;
$vat = mysql_real_escape_string($vat_array[$i]);
// mysql_query("INSERT INTO users (name, age) VALUES ('$name', '$age')");
$sql ="Insert into material_items SET category_name='$cat', item_name='$name', quantity='$q',
mrp='$mrp', vat='$vat', inv_id ='$sales_id'";
// echo $sql;
$res = mysql_query($sql) or die(mysql_error());
$sql1 = "Update stock set quantity=quantity -'$q' where item_name='$name'";
$res1 = mysql_query($sql1) or die(mysql_error());
echo "stock updated and invoice created";
}
}
}
I have first checked if item is present in purchase_stock table. (items are inserted in purchase_stock table after a purchase order is created). Then i insert in the sales table quantity which is sold. And then I write query to update stock table.
My question is do I write a insert query for stock table if no items are initially present there? Is it logically correct? Or should I keep same stock table to update quantity and items after purchase and sales transactions?
Here is an example of a stored procedure syntax
DELIMITER //
CREATE PROCEDURE GetProduct(IN param_ProductID INT)
BEGIN
SELECT *
FROM Products
WHERE ProductID = param_ProductID;
END //
DELIMITER ;
and this is how you call it from your php:
$mysqli->query("CALL GetProduct(".$param_ProductID.")");
regarding your question about inserting the the product,
you need to perform an UPSERT (insert if not exists and update if exists)
here is an example how to do it:
PHP / MySQL : Insert if doesnt exist else update
shimon :)

MySQL Update Not Updating Certain Rows

Here is my double-minded query:
$Quest = "SELECT * FROM TOAWorkorders";
$FindTechResult = mysql_query($Quest, $cxn)
or die ('The easter bunny is watching you' . mysql_error());
while ($row = mysql_fetch_array($FindTechResult))
{
if (strpos($BBT, 0, 3) != 'Sys')
{
$IdNum = $row['IdNum'];
$BBT = $row['BBT'];
$BBTArray = explode("-", $BBT);
$TechNum = $BBTArray["0"];
$Title = $BBTArray["2"];
$Name = explode(" ", $BBTArray['1']);
$FirstName = $Name["0"];
$LastName = $Name["1"];
}
echo $TechNum . ' !! ' . $FirstName . ' !! ' . $LastName . ' !! ' . $Title . '<br>';
$Quest = "UPDATE TOAWorkorders SET TechNum = '$TechNum', FirstName = '$FirstName', LastName = '$LastName', Title = '$Title' WHERE IdNum = '$IdNum'";
$result = mysql_query($Quest, $cxn) or die(mysql_error());
}
Everything works for about 2/3s of the database. That leaves 33,000 rows that are not updated. I cannot find any difference between the data that works and the data that doesn't.
Since you're doing an UPDATE, and you say the rest of the code works (meaning, I hope, that you get 109,112 echo'ed results), it must be that the ID isn't being found (WHERE IdNum = '$IdNum').
Try preceding that command with "SELECT COUNT(*) from TOAWorkorders WHERE IdNum = '$IdNum'" and see if you get 33,000 zeros when the program runs. If you do, then you have missing IdNum values in your table.
If you don't, please provide details and I'll let you know.