Can not insert php data to mysql using for() - php

i try to insert the data with php to mysql by checking the value if it exists then it will update if no then it will insert, but it fail i use for () what is wrong with my script?
if(isset($_POST['submit'])){
$fieldA = $_POST['fieldA'];
$fieldB = $_POST['fieldB'];
$fieldC = $_POST['fieldC'];
$fieldD = $_POST['fieldD'];
if (empty($fieldA)) {
echo 'fieldA cannot empty';
}
else
{
for ($i=1; $i<= $nomer; $i++) {
$query = mysql_query("SELECT * FROM tb1 ".
"WHERE fieldA = '$fieldA' ".
"AND fieldB = '$fieldB' ".
"AND fieldC = '$fieldC' ".
"AND fieldD = '$fieldD'");
$get1 = mysql_fetch_assoc($query);
$get2 = mysql_num_rows($query);
if ($get2 != 0) {
mysql_query("UPDATE tb1 SET kd_kelas = '2' ".
"WHERE fieldA = '$fieldA' ".
"AND fieldB = '$fieldB' ".
"AND fieldC = '$fieldC' ".
"AND fieldD = '$fieldD'");
} else {
mysql_query("INSERT INTO tb1(fieldA, fieldB, ".
"fieldC, fieldD) VALUES ".
"('$fieldA', '$fieldB', ".
"'$fieldC', '$fieldD')");
}
}
}
//re-direct
$go = "mydata.php";
redirect($go);
}

All the methods related with mysql_* is deprecated now. Use mysqli_*.
And try this snippet:
if (isset($_POST['submit']) && !empty($_POST['fieldA'])) {
$fieldA = $_POST['fieldA'];
$fieldB = $_POST['fieldB'];
$fieldC = $_POST['fieldC'];
$fieldD = $_POST['fieldD'];
for ($i = 1; $i <= $nomer; $i++) {
$sql = sprintf("SELECT * FROM tb1 WHERE fieldA = '%s' AND fieldB = '%s' AND fieldC = '%s' AND fieldD = '%s'",
$fieldA, $fieldB, $fieldC, $fieldD);
$result = mysqli_query($link, $sql);
if (mysqli_num_rows($result) > 0) {
$updateSql = sprintf("UPDATE tb1 SET kd_kelas = '2' WHERE fieldA = '%s' AND fieldB = '%s' AND fieldC = '%s' AND fieldD = '%s'",
$fieldA, $fieldB, $fieldC, $fieldD);
mysqli_query($link, $updateSql);
}
else {
$insertSql = sprintf("INSERT INTO tb1(fieldA, fieldB,fieldC, fieldD) VALUES ('%s','%s','%s','%s')", $fieldA,
$fieldB, $fieldC, $fieldD);
mysqli_query($link, $insertSql);
}
}
//re-direct
$go = "mydata.php";
redirect($go);
}
here $link is the connection string
$link = mysqli_connect('localhost', 'root', 'password', 'database');

Related

Migrating PHP 7 to 8 - Object's constructor is not called [duplicate]

This question already has answers here:
What's difference between __construct and function with same name as class has? [duplicate]
(5 answers)
PHP7 Constructor class name
(2 answers)
Closed 7 months ago.
We need to migrate our live online store from PHP 7.x to PHP 8.x
My main XAMPP folder is running PHP 7.4.3, and I've installed the latest XAMPP (8.1.6) into another folder.
The main site seems to work fine when I run the PHP 8 instance, but the basket object doesn't seem to be starting.
I can tell as I can echo out $cartid from PHP 7 but not 8.
Have I missed a config option I need to edit, or has something changed in the way PHP 8.x handles global variables or objects?
basket.php
...
include ("sqlcart.php");
$cart = new basket;
...
sqlcart.php
class basket
{
var $items;
var $empty;
var $cartid;
var $voucher_id_set;
function basket()
{
global $cartid;
global $vat_rate;
global $voucher_id_set;
global $outmail;
global $conn;
global $_COOKIE;
global $_POST;
$voucher_id_set = 0;
$number = 0;
if (isset($_COOKIE["cart_id"])) {
$cartid = ClearString(substr($_COOKIE["cart_id"], 0, 10));
$testcartid = $cartid;
settype($testcartid, "integer");
if ($testcartid > 0) {
$strsql = "SELECT * from g_tempbasket where basket_id = '" . clearstring(substr($cartid, 0, 10)) . "'";
$result = safedb_query($strsql);
$number = mysqli_num_rows($result);
} else {
$number = 0;
}
} else {
// force cart creation
$number = 0;
}
if ($number == 0) {
$todaydate = date("Y-m-d h:i:s");
$strsql = "INSERT INTO g_tempbasket (basket_id,date) ";
$strsql .= "VALUES (NULL,'$todaydate')";
safedb_query($strsql);
$newcartid = mysqli_insert_id($conn);
if ($outmail == 1) {
setcookie("cart_id", $newcartid, time() + (24 * 3600), "", ".website.co.uk", 1);
setcookie("voucher_id", "", 0, "", ".website.co.uk", 1);
} else {
setcookie("cart_id", $newcartid, time() + (24 * 3600));
setcookie("voucher_id", "", 0);
}
$cartid = $newcartid;
}
$strsql = "SELECT t.product_id, p.descript, p.cost, t.qty ";
$strsql .= "FROM g_tempbasket AS tb, g_product AS p, g_tempitems AS t ";
$strsql .= "WHERE tb.basket_id = t.basket_id ";
$strsql .= "AND t.product_id = p.product_id ";
$strsql .= "AND tb.basket_id = " . $cartid;
$result = safedb_query($strsql);
$number = mysqli_num_rows($result);
mysqli_free_result($result);
//$this->items=$result;
if ($number != 0) {
$this->empty = false;
} else {
$this->empty = true;
}
} //function
function additem($id, $name, $addcount)
{
global $cartid;
// Get product info to add
$strsql = "SELECT descript, cost, no_vat FROM g_product ";
$strsql .= "WHERE product_id = '" . $id . "'";
$prodaddresult = safedb_query($strsql);
$prodaddrow = mysqli_fetch_assoc($prodaddresult);
$prodname = $prodaddrow["descript"];
$prodcost = $prodaddrow["cost"];
$prodnovat = $prodaddrow["no_vat"];
$strsql = "SELECT qty FROM g_tempitems ";
$strsql .= "WHERE basket_id = " . $cartid;
$strsql .= " AND product_id = '" . $id . "'";
$result = safedb_query($strsql);
$number = mysqli_num_rows($result);
$strsqls = "SELECT prod_code FROM g_ship_options ";
$strsqls .= "WHERE prod_code = '" . $id . "'";
$sresult = safedb_query($strsqls);
$snumber = mysqli_num_rows($sresult);
if ($number == 0) {
if ($id == "" || $addcount < 1) { // Basic anti-bot validation
header("Location: index.php");
exit;
}
if ($snumber != 0) { // Item is shipping - mark in basket
$strsql = "INSERT INTO g_tempitems ";
$strsql .= "(basket_id, product_id, qty, shipping, descript, cost, no_vat) ";
$strsql .= "VALUES (".$cartid.", '".$id."', ".$addcount.", 1, '".$prodname."', '".$prodcost."', '".$prodnovat."')";
} else { // Non-shipping item
$strsql = "INSERT INTO g_tempitems ";
$strsql .= "(basket_id, product_id, qty, shipping, descript, cost, no_vat) ";
$strsql .= "VALUES (".$cartid.", '".$id."', ".$addcount.", 0, '".$prodname."', '".$prodcost."', '".$prodnovat."')";
}
} else {
if ($id == "") { // Basic anti-bot validation
header("Location: index.php");
exit;
}
$currow = mysqli_fetch_assoc($result);
$current = $currow["qty"];
$new = $current + $addcount;
if ($new <= 0) {
$new = 1;
}
$strsql = "UPDATE g_tempitems ";
$strsql .= "SET qty = ".$new.", ";
$strsql .= "descript = '".$prodname."', ";
$strsql .= "cost = ".$prodcost.", ";
$strsql .= "no_vat = ".$prodnovat." ";
$strsql .= "WHERE basket_id = ".$cartid." ";
$strsql .= "AND product_id = '".$id."'";
}
mysqli_free_result($result);
safedb_query($strsql);
$this->empty = false;
}
Propably incompatible changes.
From docs:
Methods with the same name as the class are no longer interpreted as constructors. The __construct() method should be used instead.
Source: https://www.php.net/manual/en/migration80.incompatible.php

Change SQL Query to a prepared statement with condition

I'm trying to change this query to a query with prepared statement, but I have some problem because of conditions.
This is my basic query :
function ResponseByQuery($link,$idQuery,$Boutique=null, $agency=null){
$from_agence = "";
$req_agence = "";
$req_boutique = "";
if($Boutique!=null){
$req_boutique = " AND C.idUser ='" . $Boutique . "' ";
}
if($agency!=null){
$from_agence = ", infos_client as IRC2";
$req_agence = " AND IRC.idClient = IRC2.idClient
AND IRC2.valueInfo = '". $agency."'";
}
$sql = "SELECT distinct(C.idClient), R.indiceRequete
FROM `infos_client` as IRC, client as C, user as U, requete as R ".$from_agence."
WHERE IRC.idQuery='" . $idQuery . "'".
$req_boutique.
"AND IRC.idCl = C.idCl
AND C.idUser=U.idUser".$req_agence;
$result = mysqli_query($link,$sql) or die("Query (- $sql -) failed");
$count = mysqli_num_rows($result);
}
I changed it to this :
function ResponseByQuery($link,$idQuery,$Boutique=null, $agency=null){
$from_agence = "";
$req_agence = "";
$req_boutique = "";
if($Boutique!=null){
$req_boutique = " AND C.idUser ='" . $Boutique . "' ";
}
if($agency!=null){
$from_agence = ", infos_client as IRC2";
$req_agence = " AND IRC.idClient = IRC2.idClient
AND IRC2.valueInfo = '". $agency."'";
}
$sql = "SELECT distinct(C.idClient), R.indiceRequete
FROM `infos_client` as IRC, client as C, user as U, requete as R ".$from_agence."
WHERE IRC.idQuery =?".
$req_boutique.
"AND IRC.idCl = C.idCl
AND C.idUser=U.idUser".$req_agence;
$stmt = $link->prepare($sql);
$stmt->bind_param('i', $idQuery);
$result = $stmt->execute() or die("Query (- $sql -) failed");
$result = $stmt->get_result();
$count = mysqli_num_rows($result);
}
but I don't know how can I change conditions($req_boutique,$req_agence) to prepared statement?
You can replace the inlined variables in your $req_boutique and $req_agence conditions with placeholders, and then conditionally bind values to them:
if($Boutique!=null){
$req_boutique = " AND C.idUser = ? ";
}
if($agency!=null){
$from_agence = ", infos_client as IRC2";
$req_agence = " AND IRC.idClient = IRC2.idClient
AND IRC2.valueInfo = ? ";
}
$sql = "SELECT distinct(C.idClient), R.indiceRequete
FROM `infos_client` as IRC, client as C, user as U, requete as R ".$from_agence."
WHERE IRC.idQuery =? ".
$req_boutique.
"AND IRC.idCl = C.idCl
AND C.idUser=U.idUser".$req_agence;
$stmt = $link->prepare($sql);
$types = 'i';
$vars = [$idQuery];
if ($Boutique != null) {
$types .= 's';
$vars[] = $Boutique;
}
if ($agency!= null) {
$types .= 's';
$vars[] = $agency;
}
$stmt->bind_param($types, ...$vars);

How to read data from database change them and update database

I need to read data from database then edit these data with php and update database with these data.
I can get data from database but not able to write them back (I add another query to see if value is changed)
I’ve tried to use phpMyAdmin to see if values are changed but they are stil
same
$POWER = "";
if ($pressed == "1") {
echo "pressed\n";
$sql = "SELECT `POWER` FROM `VolleyTest` WHERE ID = 1";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_row($result)) {
$POWER = $row[0];
echo "pressed power request $row[0]\n";
}
if ($POWER == "ON") {
$sql = 'UPDATE `VolleyTest` SET `POWER`=\"OFF\" WHERE ID = 1';
$conn->query($sql);
echo " POWER ON to OFF\n";
} else if ($POWER == "OFF") {
$sql = 'UPDATE `VolleyTest` SET `POWER`=\"ON\" WHERE ID = 1';
$conn->query($sql);
echo " POWER OFF to ON\n";
}
}
$sql = "SELECT `POWER` FROM `VolleyTest` WHERE ID = 1";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_row($result)) {
$POWER = $row[0];
echo "$row[0]\n";
}
echo $POWER; //. " ". $pressed . " " . $_POST['key'];
You dont need to escape double quotes inside a single quoted string.
Doing that generates a string like this
UPDATE `VolleyTest` SET `POWER`=\"ON\" WHERE ID = 1
So this may work
$POWER = "";
if ($pressed == "1") {
echo "pressed\n";
$sql = "SELECT `POWER` FROM `VolleyTest` WHERE ID = 1";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_row($result)) {
$POWER = $row[0];
echo "pressed power request $row[0]\n";
}
if ($POWER == "ON") {
$sql = 'UPDATE `VolleyTest` SET `POWER`="OFF" WHERE ID = 1';
$conn->query($sql);
echo " POWER ON to OFF\n";
} else if ($POWER == "OFF") {
$sql = 'UPDATE `VolleyTest` SET `POWER`="ON" WHERE ID = 1';
$conn->query($sql);
echo " POWER OFF to ON\n";
}
}
$sql = "SELECT `POWER` FROM `VolleyTest` WHERE ID = 1";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_row($result)) {
$POWER = $row[0];
echo "$row[0]\n";
}
echo $POWER; //. " ". $pressed . " " . $_POST['key'];

How to include insert query inside for loop using php?

User will enter like more than one payment card 1.00,cash 2.00,card 10,00,cash 20.00 etc...After these all values insert into payment_details table one by one along with current date.So after this i need to insert data to another table called moneybox table.
Count of total cash and total card will store into money box group by current date.Always two rows ie; card and cash will be there in money table,going to total of cash and card will be store based on current date.
As far as I understand the requirements, this may help...
<?php
if (isset($_POST["getamount"])) {
$getinvoiceid = $_POST['getinvoiceid'];
$getstorepaymode = $_POST['getstorepaymode'];
$getamount = $_POST['getamount'];
$sql1 = "select date from moneybox order by ID desc limit 1";
$result1 = mysqli_query($link, $sql1);
$row1 = mysqli_fetch_array($result1);
//echo json_encode($row1);
$last_moneybox_created_date = $row1['date'];
$sqlclosebalcash = "select closing_balance from moneybox where date='$last_moneybox_created_date' and type='cash'";
$resultclosebal_cash = mysqli_query($link, $sqlclosebalcash);
$rowclosebal_cash = mysqli_fetch_array($resultclosebal_cash);
//echo json_encode($row1);
//$last_moneybox_closingbalanacecash = $rowclosebal_cash['closing_balance'];
$sqlclosebalcard = "select closing_balance from moneybox where date='$last_moneybox_created_date' and type='bank'";
$resultclosebal_card = mysqli_query($link, $sqlclosebalcard);
$rowclosebal_card = mysqli_fetch_array($resultclosebal_card);
//$last_moneybox_closingbalanacecard = $rowclosebal_card['closing_balance'];
$tz = 'Asia/Dubai'; // your required location time zone.
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
$todayDate = $dt->format('Y-m-d');
if ($rowclosebal_cash['closing_balance'] == '') {
$last_moneybox_closingbalanacecash = "0.00";
} else {
$last_moneybox_closingbalanacecash = $rowclosebal_cash['closing_balance'];
}
if ($rowclosebal_card['closing_balance'] == '') {
$last_moneybox_closingbalanacecard = "0.00";
} else {
$last_moneybox_closingbalanacecard = $rowclosebal_card['closing_balance'];
}
for ($count = 0; $count < count($getamount); $count++) {
$payamt_clean = $getamount[$count];
$getstorepaymode_clean = $getstorepaymode[$count];
date_default_timezone_set('Asia/Dubai');
$created = date("y-m-d H:i:s");
$query = 'INSERT INTO payment_details (invoiceID,paymentMode,Amount,created)
VALUES ("' . $getinvoiceid . '" , "' . $getstorepaymode_clean . '", "' . $payamt_clean . '", "' . $created . '");
';
mysqli_query($link, $query);
// check whether card or cash or both rows are already there or not
$sql1 = "select * from moneybox WHERE date='$todayDate' AND type='cash' ";
$resultcash = mysqli_query($link, $sql1);
if(mysqli_num_rows($resultcash)) {
$cashMode = 1;
}
else {
$cashMode = 0;
}
$sql1 = "select * from moneybox WHERE date='$todayDate' AND type='bank' ";
$resultcard = mysqli_query($link, $sql1);
if(mysqli_num_rows($resultcard)) {
$cardMode = 1;
}
else {
$cardMode = 0;
}
$cal_closingbalancecash = $last_moneybox_closingbalanacecash - $payamt_clean;
$cal_closingbalancecard = $last_moneybox_closingbalanacecard - $payamt_clean;
switch($getstorepaymode_clean) {
case "CASH":
if($cashMode === 0) {
echo 'Different Date cash'; //insert happen based on the type
$last_moneybox_created_date = $todayDate;
$cashMode = 1;
$query = "INSERT INTO moneybox (type,inflow,date)
VALUES ('cash','$payamt_clean','$todayDate');";
}
else {
echo 'Same Date cash'; //update happen based on type and date
$query = "UPDATE moneybox SET
inflow = inflow + $payamt_clean,
closing_balance= opening_balance + inflow - outflow
WHERE type = 'cash' and date = '$todayDate';";
}
break;
case "CARD":
if($cardMode === 0) {
echo 'Different Date card'; //insert happen based on the type
$last_moneybox_created_date = $todayDate;
$cardMode = 1;
$query = "INSERT INTO moneybox (type,inflow,date)
VALUES ('bank','$payamt_clean','$todayDate');";
}
else {
echo 'Same Date card'; //update happen based on type and date
$query = "UPDATE moneybox SET
inflow = inflow + $payamt_clean,
closing_balance= opening_balance + inflow - outflow
WHERE type = 'bank' and date = '$todayDate';";
}
break;
} // end switch case
if (mysqli_query($link, $query)) {
echo 'paydetails Inserted';
}
else {
echo "Error: " . $query . "<br>" . mysqli_error($link);
}
}
}
?>

PHP MySQL search with multiple criteria

I have a search form in a website and would like to have several search terms which is input by the user to perform db search, terms as below:
Keywords
Property For (Sale, Rent...)
Property Type (Apartment, Terrace House...)
State
Min Price
Max Price
Here is script to perform search with above term's input
public function get_property_list_by_search($start, $per_page, $keyword, $prop_for, $min, $state, $ptype, $max, $mysqli)
{
if(empty($start) && empty($per_page))
{
return 0;
}
$start = preg_replace('/[^0-9]/', '', $mysqli->real_escape_string($start));
$per_page = preg_replace('/[^0-9]/', '', $mysqli->real_escape_string($per_page));
$keyword = $mysqli->real_escape_string(stripslashes($keyword));
$prop_for = $mysqli->real_escape_string(stripslashes($prop_for));
$state = $mysqli->real_escape_string(stripslashes($state));
$ptype = $mysqli->real_escape_string(stripslashes($ptype));
$min_price = self::num_clean($mysqli->real_escape_string($min));
$max_price = self::num_clean($mysqli->real_escape_string($max));
$t1 = '';
$t2 = '';
$t3 = '';
$t4 = '';
$t5 = '';
if(isset($keyword) && !empty($keyword)){
$t1 = " AND `proj_title` LIKE '%".$keyword."%' OR `proj_addr` LIKE '%".$keyword."%' OR `proj_area` LIKE '%".$keyword."%'";
}
if(isset($prop_for) && !empty($prop_for)){
$t2 = " AND `proj_for`='".$prop_for."'";
}
if(isset($state) && !empty($state)){
$t3 = " AND `state`='".$state."'";
}
if(isset($ptype) && !empty($ptype)){
$t4 = " AND `proj_cat`='".$ptype."'";
}
//min & max
if((isset($min_price) && !empty($min_price)) && (isset($max_price) && !empty($max_price))){
$t5 = " AND `price` BETWEEN '".$min_price."' AND '".$max_price."'";
}
//min only
if(!empty($min_price) && empty($max_price)){
$t5 = " AND `price` >= '".$min_price."'";
}
//max only
if(empty($min_price) && !empty($max_price)){
$t5 = " AND `price` <= '".$max_price."'";
}
$sql = $mysqli->query("SELECT * FROM `project` WHERE `status`='1' ".
$t1." ".$t2." ".$t3." ".$t4." ".$t5." ".
"ORDER BY `posted_date` DESC LIMIT ".$start.", ".$per_page);
if($sql->num_rows > 0){
return $sql;
}else{
return false;
}
}
The query output will something like:
SELECT * FROM `project`
WHERE `proj_title` LIKE '%keywords%'
OR `proj_addr` LIKE '%keywords%'
OR `proj_area` LIKE '%keywords%'
AND `proj_for`='Sale' AND `state`='Somewhere' AND `proj_cat`='8' AND `price` BETWEEN '250000' AND '600000'
(Datatype for price is DECIMAL(10,2), it stored value like 250000.00)
However, the returned results is not like expected (not accurate), its also will come out a result with price more than 600000 and project category which is out of '8' which is not fancy for the end user to searching in the website.
is there any way to refine on the query to perform more specific?
Instead of taking these variables you should use ".=" operator.
/* $t1 = '';
$t2 = '';
$t3 = '';
$t4 = '';
$t5 = '';
*/
$q = "SELECT * FROM `property` WHERE `status`='1' ";
// You need to enclose all **OR** logical tests in parenthesis.
// Moreover most of the usages of isset function are useless,
// as your are initializing many variables
if($keyword && !empty($keyword)){
$q .= " AND (`p_title` LIKE '%".$keyword."%' OR `address` LIKE '%".$keyword."%' OR `area` LIKE '%".$keyword."%')";
}
if($prop_for && !empty($prop_for)){
// If you are using double quotes you really don't need handle to concatenation.
$q .= " AND `p_for`='$prop_for'";
}
if($state && !empty($state)){
$q .= " AND `state`='$state'";
}
if($ptype && !empty($ptype)){
$q .= " AND `p_category`='$ptype'";
}
//min only
if($min_price && !empty($min_price)){
$q .= " AND `price` >= '".$min_price."'";
}
//max only
if($max_price && !empty($max_price)){
$q .= " AND `price` <= '$max_price'";
}
// When you are not using OFFSET keyword,
//the first number after LIMIT keyword should be the number of records
$q .= " ORDER BY `posted_date` DESC LIMIT $per_page , $start;";
$sql = $mysqli->query($q);
You're going to need parentheses.
SELECT * FROM `project` WHERE (`proj_title` LIKE '%keywords%' OR `proj_addr` LIKE '%keywords%' OR `proj_area` LIKE '%keywords%') AND `proj_for`='Sale' AND `state`='Somewhere' AND `proj_cat`='8' AND `price` BETWEEN '250000' AND '600000'
Without the parentheses it just has to match one of the criteria before the last OR.
if(isset($_SESSION['login']))
{
echo "<div align=\"right\"><strong> Home |
Signout|
Profile</strong></div>";
}
else
{
echo " ";
}
$con= mysql_connect("localhost","root","");
$d=mysql_select_db("matrimonial",$con);
$gender=$_POST['gender'];
$age1=$_POST['age1'];
$age2=$_POST['age2'];
$city=$_POST['city'];
$subcast=$_POST['subcast'];
$result=mysql_query("select * from matri where gender='$gender' and age between '$age1' and '$age2' and city='$city' and subcast='$subcast'");
if($gender && !empty($gender))
{
$result .= " AND `gender`='$gender'";
}
if($age1 && !empty($age1)){
$result .= " AND `age`='$age1'";
}
if($age2 && !empty($age2)){
$result .= " AND `age`='$age2'";
}
if($city && !empty($city)){
$result .= " AND `city`='$city'";
}
if($subcast && !empty($subcast)){
$result .= " AND `subcast`='$subcast'";
}
$result .= " select * from ";
$sql = $mysql->query($result);
how to run this code
On the price difference you should do a if the price if between the 2 values else only 1 value.

Categories