I am quite new in php and trying to write my first scripts. I put values in a database. If a record has to be changed, the user can choose the id of the record that has to be changed. Some datas will remain, only read and some f.e. remarks can be changed. I have no problem with getting the datas from the database, but with storing the changed values.
User can choose the record to be changed:
public function bejelentesKivalasztas(){
$this->kapcsolodas();
$sqlHibabejelentesekTablabol = "SELECT bejelentesID FROM hibarogzites";
$this->hibabejelentesekTablabol = mysqli_query($this->kapcs, $sqlHibabejelentesekTablabol);
$sorokSzama = mysqli_num_rows($this->hibabejelentesekTablabol);
global $adat;
global $i;
$adat = [];
print("<select class='textarea' name='bejelentes_ID' id='bejelentes_ID' style='width: 220px'>");
for ($i=0; $i<$sorokSzama; $i++){
$adat[$i] = mysqli_fetch_array($this->hibabejelentesekTablabol);
print("<option value='" . $adat[$i]['bejelentesID'] . "'> " . $adat[$i]['bejelentesID'] . " </option>");
}
}
Necessary datas will be recalled and printed with the possibility to change some of them:
<?php
if(isset($_POST['bejelentesKivalasztas'])){
$bejelentesID = $_POST['bejelentes_ID'];
$boltCimBeolvasas = new adatlekerdezes($bejelentesID);
$boltCimBeolvasas ->boltCimBeolvasas($bejelentesID);
}
?>
public function boltCimBeolvasas(){
if(isset($_POST['bejelentesKivalasztas'])){
$bejelentesID = $_POST['bejelentes_ID'];
$this->kapcsolodas();
global $boltSzam, $boltVaros, $boltIrsz, $boltUtca, $bejelentesID;
$this->bejelentesID = $bejelentesID;
$this->egyBoltkivalasztas();
$sqlReadBoltAddressFromTable= "SELECT * FROM boltok WHERE boltID = '" . $this->boltID ."'";
$boltCimBeolvasas = mysqli_query($this->kapcs,$sqlReadBoltAddressFromTable);
$this->adat2 = mysqli_fetch_array($boltCimBeolvasas);
$this->boltSzam = $this->adat2[1];
$boltSzam = $this->boltSzam;
$boltIrsz = $this->adat2[2];
$boltVaros = $this->adat2[3];
$boltUtca = $this->adat2[4];
$this->bejelentesLehivas($this->bejelentesID);
$this->megjegyzesBeolvasas($this->bejelentesID);
}
}
public function megjegyzesBeolvasas(){
$this->kapcsolodas();
global $bejelMegjegyz;
$hibabejelentesekTablabol = [];
$this->sqlHibabejelentesekTablabol = "SELECT megjegyzesSzoveg FROM hibarogzites where bejelentesID = '" . $this->bejelentesID . "'";
$hibabejelentesekTablabol = mysqli_fetch_array(mysqli_query($this->kapcs, $this->sqlHibabejelentesekTablabol));
global $adat3;
$adat3 = [];
$this->adat3 = $hibabejelentesekTablabol;
$bejelMegjegyz = $this->adat3[0];
return $bejelMegjegyz;
}
But when restoring should follow, the ID (bejelentesID) gets lost and as this, data will not change.
public function bejelentesMod($intezkedes, $megjegyzes, $szerelo, $bejelentesID){
$this->kapcsolodas();
$sqlSzereloAdat = "SELECT *
FROM szerelo
WHERE szerelo_nev = '" . $szerelo . "'";
$szereloAdat = mysqli_fetch_array(mysqli_query($this->kapcs, $sqlSzereloAdat));
print("Szerelőadat: " . $szereloAdat['szereloID'] . " eddig / ");
$this->szereloID = $szereloAdat['szereloID'];
$this->intezkedesID = $intezkedes;
$this->bejelentesID = $bejelentesID;
print("intID: " . $this->intezkedesID);
print(" / bejelID: " . $this->bejelentesID);
$sqlHibabejelentesFrissites = "UPDATE hibarogzites SET megjegyzesSzoveg = '" . $megjegyzes . "', intezkedesID = '" . $this->intezkedesID . "', szereloID = '" . $this->szereloID . "', felhasznaloID = '" . $this->felhasznaloID . "' WHERE bejelentesID = '" . $this->bejelentesID . "'";
$hibabejelentesFrissites = mysqli_query($this->kapcs, $sqlHibabejelentesFrissites);
print(', $sqlhibabejelentesFrissítés értéke: ' . $sqlHibabejelentesFrissites);
if(!mysqli_connect_errno()){
$this->message = "A bejegyzés módosítva";
}
else{
$this->message = "A bejegyzés módosítása nem sikerült";
}
// header('Location: hibabejelentesek.php');
}
From that point that the id gets lost, the update cannot happen. I tried the mysql command at it worked in the sql programm directly. I inserted the
print("intID: " . $this->intezkedesID);
print(" / bejelID: " . $this->bejelentesID);
in function bejelentesMod to see what was the problem.
Maybe session can be the solution - but the id must be changed when another record must be changed. Can I use this session variable despite of that?
I suppose there are several problems with this code, but as I wrote - this is my first one. Even though I hope someone can me help how to get it work.
Thanks in advance for any help.
Related
I have a table which includes a row for each day of the week.
Each row contains 2 input fields.
I am wanting to click one save button which will update all rows from the table into seperate MySQL rows.
I have the below code to insert new rows (which works fine) but wondering how this can be changed to an UPDATE statement?
$insertArr = array();
for ($i=0; $i<$cnt; $i++) {
$insertArr[] = "('"
. mysql_real_escape_string($_GET['Actual'][$i]) .
"', '"
. mysql_real_escape_string($_GET['Period'][$i]) .
"', '"
. mysql_real_escape_string($_GET['AddedBy'][$i]) .
"', '"
. mysql_real_escape_string($_GET['Date'][$i]) .
"', '"
. mysql_real_escape_string($_GET['Employee'][$i]) .
"', '"
. mysql_real_escape_string($_GET['Rotered'][$i]) . "')";
}
$query = "INSERT INTO hr_employee_rostered_hours (Actual, PeriodID, AddedBy, DateOfHours, EmployeeUniqueID, Rotered) VALUES " . implode(", ", $insertArr);
mysql_query($query) or trigger_error("Insert failed: " . mysql_error());
}
The mysql extension has been deprecated in PHP, and I strongly advice against using it.
Assuming that you're still getting the values that you want to update using the array,
Here is a link about PDO (not official docummentation) that helped me out when I first started with PHP and PDO
Here's an example using PDO
$updateq = "UPDATE hr_employee_rostered_hours SET (Actual = :actualvalue, PeriodID = :periodid, AddedBy = :addedby,DateOfHours = :dateofhrs, Rotered = :rotered ) WHERE EmployeeUniqueID = :employeeid";
$updatex = $dbh->prepare($updateq);
$updatex->bindValue(":actualvalue",$insertArr[0]);
$updatex->bindValue(":periodid",$insertArr[1]);
$updatex->bindValue(":addedby",$insertArr[2]);
$updatex->bindValue(":dateofhrs",$insertArr[3]);
$updatex->bindValue(":periodid",$insertArr[5]);
$updatex->bindValue(":employeeid",$insertArr[4]);
$updatex->execute();
You can use this code to update in MySQL.
for ($i = 0; $i < count($insertArr); $i++){
$var_to_update = implode(", ", $insertArr[$i]);
$actual = $var_to_update[0];
$periodID = $var_to_update[1];
$addedby = $var_to_update[2];
$dateofhour = $var_to_update[3];
$employeeUniqueID = $var_to_update[4];
$rotered = $var_to_update[5];
$query = "UPDATE hr_employee_rostered_hours SET (Actual = $actual , PeriodID = $periodID, AddedBy = $addedby, DateOfHours = $dateofhour, EmployeeUniqueID = $employeeUniqueID, Rotered = $rotered) WHERE EmployeeUniqueID = $employeeUniqueID";
$result = mysql_query($sql);
if ($result === FALSE)
{
die(mysql_error());
}
}
Hi and thanks for reading.
I have been using this for a while on an old php5 running on a Windows XP box. Recently I moved everything to a php7.0 running on a linux box.
It still runs fine in the old environment but not on the new one. Any suggestions as to where I am going wrong?
Here is the data going in;
http://192.168.0.2/test/index2.php?doing=advicepart3&from=advicepart3update&id=5096&delivered=5&delivered1&delivered3=&discount=0.00&carriage=0.00
Basically it is delivering part of an order.
if (preg_match("/^delivered([0-9]+)$/", $key, $matches) == 1) {
$id = $matches[1];
$sql1a = "SELECT QUANTITY, DELIVERED FROM salesitems WHERE ID = '" . $id . "' ORDER BY ID DESC LIMIT 1";
$result1a = $conn->query($sql1a);
if (mysqli_query($conn, $sql1a))
{
}
else
{
print "Error: " . $sql1a . "<br>" . mysqli_error($conn) . " Contact support";
}
if ($result1a->num_rows > 0) {
while($row1a = $result1a->fetch_assoc())
{
$ordered = $row1a['QUANTITY'];
$alreadydelivered = $row1a['DELIVERED'];
}
}
$updatedelivered = $alreadydelivered + $value;
if ($updatedelivered > $ordered)
{
$updatedelivered = $ordered;
}
$outstanding = $ordered - $updatedelivered;
$sql = "UPDATE salesitems SET DELIVERED = '". $updatedelivered ."', OUTSTANDING = '". $outstanding ."' WHERE ID = '" . $id . "'";
if (mysqli_query($conn, $sql))
{
}
else
{
print "Error: " . $sql . "<br>" . mysqli_error($conn) . " Contact support";
}
}
Many thanks in advance for any suggestions.
No wonder there wasn't an error - there wasn't anything wrong with it. Problem was the php I wrote had a problem. Each of the delivered should have had a number appended to them (taken from a query) but the query wasn't reading properly.
Thank you for making me look elsewhere.
function get_user_id()
{
global $db;
$userid = NULL;
if (!empty($_COOKIE['PHPSESSID']))
{
$result = $db->execute("
SELECT profile_id
FROM " . TABLE_PREFIX . "profile_online
WHERE hash = '" . $db->escape_string($_COOKIE['PHPSESSID']) . "'
");
if ($row = $db->fetch_array($result))
{
$userid = $row[0];
}
}
return $userid;
}
function get_membership_id($userid)
{
global $db;
$result = $db->execute("
SELECT * FROM date_profile WHERE profile_id = '" . $db->escape_string($userid) . "'");
$mem = $db->fetch_array($result)
$membership = $mem[17];
return $membership;
}
the get_user_id is functioning fine... but the membership part i just can't get it to work..
I am trying to take the membership ids.. and make it so certain code will not run for them.
with an : if ($membership != 18 )
so it shows all everyone except the membership 18 people...
also tried this:
function get_membership_id($userid)
{
global $db;
$membership = $db->execute("SELECT `membership_type_id` FROM `date_profile` WHERE `profile_id`= '" . $db->escape_string($userid) . "'");
return $membership;
}
any help would be appreciated greatly.
missed ; here
$mem = $db->fetch_array($result);
^
You're missing semicolon after $mem = $db->fetch_array($result).
forgot to use TABLE_PREFIX constant.
SELECT * FROM " . TABLE_PREFIX . "date_profile WHERE profile_id ...
I'm trying to submit a form in a fancybox where users can add a company to a select box that exists on the modals parent page. Im doing this by submitting the modal information to a script that adds the company to my database. Then I run a query to to get all the updated companies as a group of tags. Then I am trying to pass that group of tags to the parent page as a jquery update. Im not sure if this is the best approach or where I'm going wrong.
I am attempting to use this post as a guide:
Find element on site from a fancybox iframe
But I have two problems with my code.
One: The fancybox is not closing
Two: The select box on the parent page is not updating
I am not sure where I am going wrong with my success call. The code from the Modal page is:
$("#send-message").click(function(){
$(this).closest('form').submit(function(){
return false;
});
var frm = $(this).closest('form');
if($(frm).valid()){
$("#ajax-loading").show();
var data = $(frm).serialize();
$(frm).find('textarea,select,input').attr('disabled', 'disabled');
$.post(
"../forms/company_add.php",
data,
function(data) {
if (data.success) {
// data.redirect contains the string URL to redirect to
$('#companyselect', $(parent.document)).html(data.success);
parent.$.fancybox.close();
}
else {
$("#ajax-loading").hide();
$(frm).find('textarea,select,input').removeAttr('disabled');
$("#send_message_frm").append(data.error);
}
},
"json"
);
}
});
The Code from company_add.php returns all the options tags like such:
if ($_POST) {
// Collect POST data from form
$name = filter($_POST['name']);
$conmail = filter($_POST['conmail']);
$addy = filter($_POST['addy']);
$confax = filter($_POST['confax']);
$city = filter($_POST['city']);
$state = filter($_POST['state']);
$con = filter($_POST['con']);
$conphone = filter($_POST['phone']);
$zip = filter($_POST['zip']);
}
$search1 = mysql_query("SELECT man_name FROM manufacturers WHERE man_name = '$name'");
$outcome1 = mysql_fetch_row($search1);
$num_rows1 = mysql_num_rows($search1);
$imageid1 = $outcome1[0];
$imageid1 = filter($imageid1);
if ($num_rows1 > 0) {
echo json_encode(array(
"error" => '<div class="msg-error">A company by that name already exists.</div>'
));
} else {
$stmnt = mysql_query("INSERT INTO manufacturers (manufacturer_id, man_name, man_address, man_city, man_state,man_zip, man_contact, man_phone, man_fax, man_mail) VALUES ('NULL', '" . $name . "', '" . $addy . "' ,'" . $city . "', '" . $state . "' , '" . $zip . "' , '" . $con . "' , '" . $conphone . "' , '" . $confax . "', '" . $conmail . "' )");
//echo "Duplicate WAS found:" . $answer1;
mysql_query($answer1);
//}
$resp['status'] = 'success';
if (empty($error)) {
$nada = "SELECT man_name FROM manufacturers ORDER BY man_name ASC";
$resulter = mysql_query($nada);
$comp1 = '0';
//Spit out array of companys as select boxes
$select = '<option value="">--Select one--</option>';
while ($result59 = mysql_fetch_array($resulter))
$select .= '<option value="' . $result59['man_name'] . '">' . $result59['man_name'] . '</option>';
echo json_encode(array(
"success" =>$select
));
} else {
echo json_encode(array(
"error" => '<div class="msg-error">Error: Unable to add your company at this time</div>'
));
}
}
I am new to programming and very new to Jquery so I'm hoping someone can see where I'm going wrong. I am using fancybox 2 and php.
Have you checked error console for any JavaScript errors?
You can try this anyway:
parent.$('#companyselect').html(data.success);
I looked through the stack questions and answers, but didn't see anything I could directly apply here. Maybe I'm just missing something.
The code below works fine, except when I include my where statement which refers to the value of the $wp_user_id variable.
I've checked that the variable IS actually being populated with a $user_id when the script is loaded. It appears that the value of this variable is lost right after the call to the conManager function, but I don't understand why. There doesn't appear to be anything within the ConnectionManager.php file (which defines the conManager function) which would touch this variable, so I'm at a loss.
I'm a PHP hack, so go easy on me, but what is causing me to lose the value of my variable, and how do I address it? Here's the code:
<?php
include_once("/home/evaluate/public_html/admin/php/ConnectionManager.php");
header('Content-type:text/javascript;charset=UTF-8');
$wp_user_id = $_GET["user"];
$json1=json_decode(stripslashes($_POST["_gt_json"]));
$pageNo = $json1->{'pageInfo'}->{'pageNum'};
$pageSize = $json1->{'pageInfo'}->{'pageSize'};
if(isset($json1->{'sortInfo'}[0]->{'columnId'})){
$sortField = $json1->{'sortInfo'}[0]->{'columnId'};
}
else{
$sortField = "miles_on_oil";
}
if(isset($json1->{'sortInfo'}[0]->{'sortOrder'})){
$sortOrder = $json1->{'sortInfo'}[0]->{'sortOrder'};
}
else{
$sortOrder = "ASC";
}
if($json1->{'sortInfo'}[0]->{'sortOrder'} == "defaultsort"){
$sortField = "miles_on_oil";
$sortOrder = "ASC";
}
if($json1->{'filterInfo'}[0]->{'value'} != "") {
for ($i = 0; $i < count($json1->{'filterInfo'}); $i++) {
if($json1->{'filterInfo'}[$i]->{'logic'} == "equal"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . "='" . $json1->{'filterInfo'}[$i]->{'value'} . "' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "notEqual"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . "!='" . $json1->{'filterInfo'}[$i]->{'value'} . "' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "less"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . "<" . $json1->{'filterInfo'}[$i]->{'value'} . " ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "lessEqual"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . "<=" . $json1->{'filterInfo'}[$i]->{'value'} . " ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "great"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . ">" . $json1->{'filterInfo'}[$i]->{'value'} . " ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "greatEqual"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . ">=" . $json1->{'filterInfo'}[$i]->{'value'} . " ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "like"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . " LIKE '%" . $json1->{'filterInfo'}[$i]->{'value'} . "%' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "startWith"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . " LIKE '" . $json1->{'filterInfo'}[$i]->{'value'} . "%' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "endWith"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . " LIKE '%" . $json1->{'filterInfo'}[$i]->{'value'} . "' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == ""){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . " LIKE '%" . $json1->{'filterInfo'}[$i]->{'value'} . "' ";
}
$filter .= " AND ";
}
}
else {
$filter = '';
}
//print_r ($json1);
//die;
// Temp TEsting Values
// End Temp Testing Values
$conManager = new ConManager();
$conManager->getConnection();
if($json1->{'action'} == 'load'){
//to get how many records totally.
$sql = "select count(*) as cnt from oil_analysis_data where $filter user_id = '".$wp_user_id."'";
$handle = mysql_query($sql);
$row = mysql_fetch_object($handle);
$totalRec = $row->cnt;
$sql2 = "select * from oil_analysis_data where $filter user_id = '".$wp_user_id."' ORDER BY " . $sortField . " " . $sortOrder . " limit " . ($pageNo - 1)*$pageSize . ", " . $pageSize;
$handle2 = mysql_query($sql2);
$retArray2 = array();
while($row2 = mysql_fetch_assoc($handle2)) {
// Grab Vehicle Make, Model & Year "Names" from their respective tables & insert into the array
$year = "select Name from vehicle_data_years where ID = {$row2['list1']}";
$year1 = mysql_query($year);
$year2 = mysql_fetch_assoc($year1);
$year3 = $year2['Name'];
$make = "select Name from vehicle_data_makes where ID = {$row2['list2']}";
$make1 = mysql_query($make);
$make2 = mysql_fetch_assoc($make1);
$make3 = $make2['Name'];
$model = "select Name from vehicle_data_all where ID = {$row2['list3']}";
$model1 = mysql_query($model);
$model2 = mysql_fetch_assoc($model1);
$model3 = $model2['Name'];
$row2['list1'] = $year3;
$row2['list2'] = $make3;
$row2['list3'] = $model3;
// Grab Motor oil Viscosity, Brand & Product "Names" from their respective tables & insert into the array
$visc = "select name from viscosity where id = {$row2['viscosity']}";
$visc1 = mysql_query($visc);
$visc2 = mysql_fetch_assoc($visc1);
$visc3 = $visc2['name'];
$brand = "select brandname from oil_brand where brandid = {$row2['brand']}";
$brand1 = mysql_query($brand);
$brand2 = mysql_fetch_assoc($brand1);
$brand3 = $brand2['brandname'];
$product = "select product_name from oil_data where id = {$row2['product']}";
$product1 = mysql_query($product);
$product2 = mysql_fetch_assoc($product1);
$product3 = $product2['product_name'];
$row2['viscosity'] = $visc3;
$row2['brand'] = $brand3;
$row2['product'] = $product3;
if($row2['bypass_filtration'] == 1) {
$row2['bypass_filtration'] = "<img src='http://themotoroilevaluator.com/admin/php/crud/images/checkmark.png' style='border: 0px;'>";
}
else {$row2['bypass_filtration'] = "";
}
if($row2['oil_change'] == 1) {
$row2['oil_change'] = "<img src='http://themotoroilevaluator.com/admin/php/crud/images/checkmark.png' style='border: 0px;'>";
}
else {$row2['oil_change'] = "";
}
$retArray[] = $row2;
}
$analysis_data = json_encode($retArray);
$ret = "{data:" . $analysis_data .",\n";
$ret .= "pageInfo:{totalRowNum:" . $totalRec . "},\n";
$ret .= "recordType : 'object'}";
echo $ret;
}
?>
I'm curious, why do you add a semi colon after the $wp_user_id; ? I've noticed you doing this in more than one place. This may be the culprit.
$filter user_id = '".$wp_user_id;."'";
Nevermind. It would appear that my problem actually resulted from a change in my code that I had forgotten about. I changed $_REQUEST['user'] to $_GET['user'], thinking that, in this case, since the value was being passed as a URL query string, that wouldn't be a problem.
To be honest, I'm still not entirely sure why that made a difference - although I can research that on my own. But, at any rate, changing that back corrected my problem entirely.
Thanks to those who responded, though. Even if not solutions to my actual problem, the information from both turned out to be very useful.
Any hacker can severely screw up or delete your database because of the way you use direct user provided data to build up your SQL query. Please instead read up on SQL Injection, and the use of PHP prepared statements.
Relevant