Hi im unable to apply array_diff() for when user edits the stockroom detail to replace with the new result.
Here is the edit function where i call out all the variables via sql.
function einv_editStockrm($srid,$code,$name,$desc,$remark,$cat)
{
//connect to database
base_connectDatabase();
$User = base_getUserDetail($_SESSION['uID']);
$Stockroom = einv_getStockrmDetail($srid);
base_executeSQL("UPDATE einv_stockroom
SET einv_stockrm_code='" . $code . "',
einv_stockrm_name='" . $name . "',
einv_stockrm_desc='" . $desc . "',
einv_stockrm_remark='" . $remark . "',
einv_stockrm_cat = '" . $cat . "'
WHERE einv_stockrm_id=" . $srid . "");
base_addTransactionLog('Manage Stock Room', 'Edit',
"
Stock Room Code = " . $code . " ||
Stock Room Name = " . $name . " ||
Stock Room Description = " . $desc . " ||
Stock Room Remark = " . $remark . " ||
Stock Room Category = " . $cat . "
");
Here is the array_diff() function. There may be unnecessary calling and/or lack of coding..not too sure. This set of codings result in no output. The server basically crashes. Any help on this?
//oldsr is existing stockroom data
//newsr is new stockroom data through edit function
//resultsr is the end result
<?php
$StockroomGetAllDetails = array();
$arr2 = einv_getStockrmDetailFromCode($stockroomCode);
$codearr = explode(",", $arr2['einv_stockrm_code']);
$oldsr = array($codearr);
$newsr = array($codearr);
$resultsr = array_diff($newsr, $oldsr);
if(!count(array_diff($oldsr, $newsr)) && !count(array_diff($newsr, $oldsr))) {
// Arrays are equal
} else {
// Array values are different
echo $resultsr;
}
?>
This code is for redirect.
//go to stock room page
echo '<script type="text/javascript">' . "\n";
echo 'window.location="../einventory/view_stockrm.php?id='. $srid .'";';
echo '</script>';
//close the database
base_closeDatabase();
}
This set of codes able to display the new datas added and removed accordingly :)
$oldCat = $Stockroom["einv_stockrm_cat"];
$oldCatArr = explode(",",$oldCat);
$newCatArr = explode(",",$cat);
//Debugging
//print_r($oldCatArr);
//print_r($newCatArr);
$resultCatAdd = array_diff($newCatArr, $oldCatArr);
$resultCatRemove = array_diff($oldCatArr, $newCatArr);
//Debugging
print_r($resultCatAdd);
print_r($resultCatRemove);
Related
I'm trying to save some json data that gets generated randomly . It can have 6 keys or just 3 keys as shown below.
Array sample:
sample 1:
{
"report": {
"a-key": "a-value",
"b-key": "b-value",
"c-key": "c-value",
"d-key": "d-value",
"e-key": "e-value",
"f-key": "f-value",
}
}
Sample 2:
{
"report": {
"a-key": "a-value",
"c-key": "c-value",
"f-key": "f-value",
}
}
Database Table name : plogs
columns: id,logdate, logtime, a, b, c, d, e,
id is unique key that auto increments
Below is the Php code i tried to use. I was able to successfully generate a text file for each json input without any errors.however I'm not able to save the values to the database. Can you please let me know where im making a mistake.
P.S Part of the code i got it off some tutorials
<?php
// Send `204 No Content` status code.
http_response_code(204);
// Get the raw POST data.
$data = file_get_contents('php://input');
$newfilename = date('Y-m-d-H-i-s') . ".txt";
file_put_contents($newfilename, $data);
// a new json file with one of the 2 sample arrays
$date1 = date('Y-m-d');
$time1 = date('H:i:s');
$b = NULL;
$d = NULL;
$f = NULL;
$connect = mysqli_connect("localhost", "dbuser", "dbpassword", "dbname") or die ("error"); //Connect PHP to MySQL Database
$query = '';
$array = json_decode($data, true); //Convert JSON String into PHP Array
function array_keys_exist(array $array, $keys)
{
$count = 0;
if (!is_array($keys)) {
$keys = func_get_args();
array_shift($keys);
}
foreach ($keys as $key) {
if (isset($array[$key]) || array_key_exists($key, $array)) {
$count++;
}
}
return count($keys) === $count;
}
foreach ($array as $row) //Extract the Array Values by using Foreach Loop
{
if (array_keys_exist($array, 'b-key', 'd-key', 'f-key'))
{
$query .= "INSERT INTO plogs(logdate, logtime, a, b, c, d, e, f) VALUES ('" . $date1 . "', '" . $time1 . "', '" . $row["a-key"] . "', '" . $row["b-key"] . "', '" . $row["c-key"] . "', '" . $row["d-key"] . "', '" . $row["e-key"] . "', '" . $row["f-key"] . "' ); ";
} else
{
$query .= "INSERT INTO plogs(logdate, logtime, a, b, c, d, e, f) VALUES ('" . $date1 . "', '" . $time1 . "', '" . $row["a-key"] . "', '" . $s1 . "', '" . $row["c-key"] . "', '" . $s2 . "', '" . $row["e-key"] . "', '" . $s1 . "'); ";
}
}
mysqli_multi_query($connect, $query);
mysqli_close($connect);
in the code of the foreach loop you are checking if the array keys are in the array variable, you should check in the $row variable as in:
if (array_keys_exist($row, 'b-key', 'd-key', 'f-key')) {
SIDE NOTE: remember to sanitize strings if they come from users, otherwise your code will be unsecure.
EDIT: for real security, as Dharman pointed out in comments, the proper way to proceed is to use prepared statements with parameter binding.
cheers
i have two update queries to update mysql db of the system.problem is my second update query works but my first one doesn't execute at all.
cant figure out whats going on...any help would be great
here is my php code.
$dob = $_POST["dob"];
$name = $_POST["name"];
$mob = $_POST["mobileNo"];
$home = $_POST["homeNO"];
$files = $_FILES["filep"]["name"];
echo $files;
$folder = "images/";
$uid = $_SESSION["Uid"];
if($_FILES["filep"]["error"] == 4) {
echo "no file selected";
}
move_uploaded_file($_FILES["filep"]["tmp_name"] , "$folder".$_FILES["filep"]["name"]);
$result = mysqli_query($con,"UPDATE User SET DOB = '" . $uid . "', MOBNO = '" . $mob . "', HOMENO = '" . $home . "',DOB = '" . $dob . "',IMAGE_URL = '" . $files . "' WHERE UID='" . $uid . "'");
$result = mysqli_query($con,"UPDATE User_Credentials SET NAME = '" . $name . "' WHERE CID='" . $uid . "'");
i have checked all the $name,$mob etc variables and value are passing without any problem..
I'm creating an appointment plugin, in that for already members and new members are there. in already member area the date entry is not entring into db. but when displaying the variale contains the date. i'm have been checking this from morning but didn't get what is the error. my code is:
$source = mysql_real_escape_string(trim($_POST['apdatetime']));
$datetime = explode(',', $source);
$dates = $datetime[0];
$app_time = $datetime[1];
if($app_time < 12){
$app_session = 'am';
}
else{
$app_session ='pm';
}
$splitdatet = explode('/', $dates);
$yyear = $splitdatet[2];
$mmonth = $splitdatet[1];
$ddate = $splitdatet[0];
$app_date = $yyear . "-" . $mmonth . "-" . $ddate;
if ($_POST['isnewpatient'] == "false") {
//$cSql = "select * from " . WP_contact . " where appointments_c_patientid='" . trim($_POST['ptntid']) . "' ";
$cSql = "select * from " . WP_eemail_TABLE_SUB . " where eemail_patient_id='" . trim($_POST['ptntid']) . "' ";
$data = $wpdb->get_results($cSql);
if (empty($data )) {
$err = 1;
echo "<div id='message' class='aerror'>No such patient ID exists....</div>";
} else {
#$mobile = htmlspecialchars(stripslashes($data[0]->eemail_mobile_sub));
#$email = htmlspecialchars(stripslashes($data[0]->eemail_email_sub));
#$name = htmlspecialchars(stripslashes($data[0]->eemail_name_sub));
$sqlss = "insert into " . WP_Appointments .
" (`appointments_patient_id`,`appointments_date`,`appointments_time`,`appointments_session`,`appointments_reg_date`) VALUES ('" .
mysql_real_escape_string(trim($_POST['ptntid'])) . "','" .
$app_date . "','" .
$app_time . "','" .
$app_session . "',CURRENT_TIMESTAMP() )";
$dd=$wpdb->get_results($sqlss);
var_dump($dd);
echo 'Date:'.$app_date;
// return $suc;
echo "<div id='message' class='asuccess' >Request has been sent for appointment</div>";
}
}
The output of the var_dump is array[0] and $app_date is Date:2014-10-22
The db entry is
appointments_id :393
appointments_patient_id : 9999999999
appointments_date : 0000-00-00
appointments_time : 9:00
appointments_session : am
appointments_reg_date : 2014-09-25 14:21:35
could anyone please point out the mistake in the code if any??
You should convert your string into date object like this:
$app_date = date('Y-m-d',strtotime($app_date));
I'm making a page, where depending on the HTML form data gets inserted/updated/deleted into/from the database.
As far as for the UPDATE goes, I have no more ideas how to fix it. The thing is, that you can update anything you want (for example nazwa_klubu only, if let's say you've changed your old nazwa_klubu and want to keep the new name (nazwa klubu = club name) in the database you type the name that you want to change to into Nazwa klubu in the Wprowadz zmiany form, and then in the second Nazwa klubu you type the name you want to be changed.
I believe it is a minor upgrade to make it all work, without having to put countless if cases, but it's my third day with PHP, so I'm confused.
EDIT: So basically, this function works properly, if all fields are filled. But I want it to work even if we fill some of fields - well, I hope you get my point. What's the point of UPDATE if you can't even use it correctly? Rhetorical Q.
And this is how it currently works:
UPDATE Koncerty SET nazwa_klubu = 'NewClubName', WHERE nazwa_klubu = 'OldClubName' AND
But obviously I want this to work like this:
UPDATE Koncerty SET nazwa_klubu = 'NewClubName' WHERE nazwa_klubu = 'OldClubName'
No matter how many input's I'll fill in this form. The first 5 inputs are responsible for SET side, and the second five are after WHERE clause.
Here's the code of the function
function update($table, $data)
{
$new_klub = 'nazwa_klubu = ' . '\'' . $data[data1] . '\',';
$new_adres = 'adres_klubu = ' . '\'' . $data[data2] . '\',';
$new_zespol = 'nazwa_zespolu = ' . '\'' . $data[data3] . '\',';
$new_ile = 'ilosc_czlonkow_zespolu = ' . '\'' . $data[data4] . '\',';
$new_wystep = 'data_wystepu = ' . '\'' . $data[data5] . '\',';
$klub = 'nazwa_klubu = ' . '\'' . $data[data6] . '\' AND';
$adres = 'adres_klubu = ' . '\'' . $data[data7] . '\' AND';
$zespol = 'nazwa_zespolu = ' . '\'' . $data[data8] . '\' AND';
$ile = 'ilosc_czlonkow_zespolu = ' . '\'' . $data[data9] . '\' AND';
$wystep = 'data_wystepu = ' . '\'' . $data[data10] . '\'';
if (empty($data[data1]) AND empty($data[data2]) AND
empty($data[data3]) AND empty($data[data4]) AND empty($data[data5])) {
echo '<span class="error">Zabezpieczenie: Musisz wpisac jakie zmiany chcesz wprowadzic</span>';
exit;
}
if (empty($data[data6]) AND empty($data[data7]) AND
empty($data[data8]) AND empty($data[data9]) AND empty($data[data10])) {
echo '<span class="error">Zabezpieczenie: Musisz wpisac na czym chcesz dokonac zmian</span>';
exit;
}
if (empty($data[data1])) {
$new_klub = '';
}
if (empty($data[data2])) {
$new_adres = '';
}
if (empty($data[data3])) {
$new_zespol = '';
}
if (empty($data[data4])) {
$new_ile = '';
}
if (empty($data[data5])) {
$new_wystep = '';
}
if (empty($data[data6])) {
$klub = '';
}
if (empty($data[data7])) {
$adres = '';
}
if (empty($data[data8])) {
$zespol = '';
}
if (empty($data[data9])) {
$ile = '';
}
if (empty($data[data10])) {
$wystep = '';
}
$safe_updates = "SET SQL_SAFE_UPDATES = 0";
$sql = "UPDATE $table SET
$new_klub
$new_adres
$new_zespol
$new_ile
$new_wystep
WHERE
$klub
$adres
$zespol
$ile
$wystep
";
echo $new_klub;
mysql_query($safe_updates);
$result = mysql_query($sql);
if (!$result) {
echo '<span class="error">' . mysql_error() . '</span><br>' . $sql . '';
}
else {
echo '<span class="success">Wprowadzono zmiany' . $sql . '</span><br>';
}
}
You shouldn't use stack overflow as somewhere ask questions like "Fix my code".
But, you could just put all your $new_ variables into an array
$new = array(
'klub' => 'nazwa_klubu = ' . '\'' . $data[data1] . '\',',
'adres' => 'adres_klubu = ' . '\'' . $data[data2] . '\',',
);
And then you can implode your array
$sql = implode(', ', $new);
Then you wont get trailing commas. Then use the same logic with AND and you'll get your SQL looking okay.
On my main page, when someone signs-in, i have jQuery using AJAX to 'talk' to a PHP file, and the same for when they sign-out. But, when they sign out, it is supposed to update a database index with the time they left. If they database entry for their last name doesn't exist (meaning, they didn't sign-in), it is supposed to return an error. Instead, the PHP file is saying that it IS updating a non-existant database index. i am using IF statements to achieve this. and for some reason it thinks the index does exist. I've checked the database that it is writing to and the indexes it's supposed to be updating don't exist.
Here's my code:
if ($Type == 1)
{
$mysqli = new mysqli("localhost","----","----", "----");
if (!$mysqli)
$Type = 3;
$Select = $mysqli->query("SELECT Time_Out FROM " . $Date . " WHERE Last_Name = '" . $LName . "'");
$Row = $Select->fetch_assoc();
$Row2 = $Row['Time_Out'];
if ($Row2 !== "-1") $Type = 4;
if ($Type == 1)
{if ($mysqli->query("UPDATE " . $Date . " SET Time_Out='" . $Time . "' WHERE Last_Name='" . $LName . "'"))
{}
else
{$Type = 5;}
}
$Select = $mysqli->query("SELECT Time_In FROM " . $Date . " WHERE Last_Name='" . $LName . "'");
$Row = $Select->fetch_assoc();
$Row2 = $Row['Time_In'];
$Time2 = explode(":",$Row2);
$Hour2 = $Hour - $Time2[0];
if ($mysqli->query("SELECT Hours FROM Names WHERE Last_Name='" . $LName . "'"))
{$Select = $mysqli->query("SELECT Hours FROM Names WHERE Last_Name='" . $LName . "'");
$Row = $Select->fetch_assoc();
$Row3 = $Row['Hours'];
$Auto += 1;}
$Time3 = 60-$Time2[1];
if ($Hour != 21) $Time4 = $Min;
$Time5 = $Time3+$Time4;
if ($Time2[0]+1 != $Hour)
{$Time5 = $Time5+60;}
$Total = $Time5+intval($Row3);
if ($Type == 1)
{
if ($mysqli->query("UPDATE Names SET Hours = '" . $Total . "' WHERE Last_Name = '" . $LName . "'"))
{$Auto += 1;}
else
{$mysqli->query("INSERT INTO Names (Last_Name, First_Name, Hours) VALUES ('" . $LName . "', '" . $FName . "', '" . $Total . "')");}
}
$mysqli->close();
}
if ($Type == 1) echo "Thank you " . $FName . " " . $LName . " for signing out! See you next time!";
if ($Type == 2) echo "The entered Student ID# is invalid. Please try again!";
if ($Type == 3) echo "An unexpected error has occured. Please try again!";
if ($Type == 4) echo "You have already signed out today!" . $Auto;
if ($Type == 5) echo "You didn't sign in today.";
The UPDATE sql statement will return true, even if it doesn't find any matches (it still runs correctly, it just updates 0 rows).
Change this:
if ($Type == 1)
{if ($mysqli->query("UPDATE " . $Date . " SET Time_Out='" . $Time . "' WHERE Last_Name='" . $LName . "'"))
{}
else
{$Type = 5;}
}
To this:
if ($Type == 1) {
if ($mysqli->query("SELECT * FROM " . $Date . " WHERE Last_Name='" . $LName . "'")->num_rows > 0)
$mysqli->query("UPDATE " . $Date . " SET Time_Out='" . $Time . "' WHERE Last_Name='" . $LName . "'");
else
$Type = 5;
}
You run the select query to first determine if the record exists (if num_rows property of the result is > 0) and based on that either update the record or set your return value to 5.