I have a problem with creating a query through a function (all others variables works correctly) I have a function that doesn't print variables correctly (exactly $NomiFarmacie and $day)
//The problem is present in this function
function Cicla($Periodo, $FarmacieRiordinate, $Query) {
global $tabella_calendario, $count; //them works
foreach ($Periodo as $giorno) {
$day = $giorno->format("Y-m-d");
$NomiFarmacie = addslashes($FarmacieRiordinate[$count % count($FarmacieRiordinate)]);
echo $NomiFarmacie; echo $day; //Both are correct
print_r($Query); //Queries are not completed correctly. OUTPUT Below
$count++;
}
}
$FarmacieRiordinate = $_POST['elementi'];
$DataIniziale = $_POST['data1'];
$DataFinale = $_POST['data2'];
$Query = ("UPDATE $tabella_calendario SET Farmacia='$NomiFarmacie' WHERE Data='$day'");
Cicla(CalcolaPeriodo($DataIniziale, $DataFinale), $FarmacieRiordinate, $Query);
A PORTION OF OUTPUT print_r($Query)
UPDATE calendario SET Farmacia='Array' WHERE Data='1546297200'
UPDATE calendario SET Farmacia='Array' WHERE Data='1546297200'
UPDATE calendario SET Farmacia='Array' WHERE Data='1546297200'
UPDATE calendario SET Farmacia='Array' WHERE Data='1546297200'
The problem is your $Query already be combined as string BEFORE passed into your function.
You can use vsprintf in this case.
function Cicla($Periodo, $FarmacieRiordinate, $Query) {
global $tabella_calendario, $count; //them works
foreach ($Periodo as $giorno) {
$day = $giorno->format("Y-m-d");
$NomiFarmacie = addslashes($FarmacieRiordinate[$count % count($FarmacieRiordinate)]);
echo $NomiFarmacie; echo $day; //Both are correct
$realQuery = vsprintf($Query, array($NomiFarmacie, $day));
print_r($realQuery); //Queries are not completed correctly. OUTPUT Below
$count++;
}
}
$FarmacieRiordinate = $_POST['elementi'];
$DataIniziale = $_POST['data1'];
$DataFinale = $_POST['data2'];
$Query = ("UPDATE $tabella_calendario SET Farmacia='%s' WHERE Data='%s'");
Cicla(CalcolaPeriodo($DataIniziale, $DataFinale), $FarmacieRiordinate, $Query);
You can read more about vsprintf here:
http://php.net/manual/en/function.vsprintf.php
.
Related
sqlsrv_prepare requires query parameters to be passed by reference. How do I pass values to a function and assign a value to it? Below example, if I pass a value to the function and try to set the referenced value nothing is returned. If I assign the referenced variable a value outside of the function it returns data using those values even though I assign them something else in the function.
$getNotesSQL = "SELECT pat_id as PAT_ID, note_id as NOTE_ID, CONVERT(char(10), UPDATE_DATE, 120) as UPDATE_DATE ";
$getNotesSQL .= "FROM CLARITY.dbo.HNO_INFO";
$getNotesSQL .= " WHERE ip_note_type_c = ? ";
$getNotesSQL .= " AND (UPDATE_DATE >= ? AND UPDATE_DATE <= ?)";
if (!$getNotes = sqlsrv_prepare($clarity, $getNotesSQL, array(&$noteType, &$startDate, &$endDate))) {
echo "getNotesSQL couldn't be prepared\n";
die(print_r(sqlsrv_errors(), true));
}
$note_type = strval(1);
$start_date = "2017-05-29";
$end_date = "2017-07-11";
/**
$noteType = strval(1);
$startDate = "2017-07-01";
$endDate = "2017-07-11";
*/
function getNotes($getNotes, $note_type, $start_date, $end_date) {
$noteType = $note_type;
$startDate = $start_date;
$endDate = $end_date;
if (!sqlsrv_execute($getNotes)) {`enter code here`
echo "getNotes Couldn't be executed\n";
die(print_r(sqlsrv_errors(), true));
}
$noteArray = array();
$iii=0;
while ($row = sqlsrv_fetch_array($getNotes, SQLSRV_FETCH_ASSOC)) {
// print_r($row);
$noteArray[$iii] = $row;
$iii++;
}
echo "In getNote Function iii: (" . $iii .")\n";
print_r($noteArray);
return $noteArray;
}
$fetchedNotes = getNotes($getNotes, $note_type, $start_date, $end_date);
print_r($fetchedNotes);
I'm not entirely sure on the reasoning behind it - I think it might have something to do with scope - but you need to pass-by-reference the query parameter variables into the function too.
So something like this:
function getNotes($getNotes, $note_type, $start_date, $end_date, &$noteType, &$startDate, &$endDate){
//perform query
}
Now that's a little ugly and quite annoying to maintain should the number of query parameters change. However you could group the values and query parameters into arrays and pass the arrays into the function. Like this:
function getNotes($getNotes, $values, $params){
foreach($params as $key => &$param){
$param = $values[$key];
}
// sqlsrv_execute
}
$values = [$note_type, $start_date, $end_date];
$params = [&$noteType, &$startDate, &$endDate];
$fetchedNotes = getNotes($getNotes, $values, $params);
I tried something similar to this on my users table, to test it, and it seems to work okay.
I have the following variables in my cart.php file:
<?php $readyTotal = $qty*price ?>;
Now I want to do is that if the $readyTotal > $1000 then call a file which is adding an item into the customer's cart.
($slq= msyql_query("INSERT into `table`.....value.....");
and if the value of $radyTotal < $1000;
dont add any extra item or if it has been added just remove it by calling the removal file.
($sql =mysql_query("DELETE from `table` where .......");
Please note that how to do this I want to call/include the files in my cart.php file. but i am unable to do this. is there any other way to do it or by using ajax/jquery which check every the value of $readyTotal every time when it changes.
function ad(){
$signature =getSignature();
$item = 21;
$type = 100;
$type= 0;
$sql2 = mysql_query("Select * From `temp` where `item`='$item' AND `price`= 0 AND
`signature`='$signature' AND `type`=0 AND `toppings`=0 " );
$count= mysql_num_rows($sql2);
if($count ==0){
$sql = mysql_query("INSERT INTO `temp`
(`item`,`price`,`signature`,`type`,`toppings`, `isCoupon`)
VALUES
('$item','$type','$signature','0','0', '1')");
}
}
function removeMe(){
mysql_query("DELETE FROM `temp` WHERE `item`=21 AND `signature`='".getSignature()."'");
}
When I try the above function individual file it works fine, but when i use both in it does not woks please.... what is wrong with this...
<?php
include_once("customfunctionfile.php");
$object = new quiz;
$readyTotal = $qty*price ;
if($readyTotal > 1000){
$object->ad();
}else{
$object->removeMe();
}
?>;
customfunctionfile.php
class quiz{
function ad(){
$signature =getSignature();
$item = 21;
$type = 100;
$type= 0;
$sql2 = mysql_query("Select * From `temp` where `item`='$item' AND `price`= 0 AND
`signature`='$signature' AND `type`=0 AND `toppings`=0 " );
$count= mysql_num_rows($sql2);
if($count ==0){
$sql = mysql_query("INSERT INTO `temp`
(`item`,`price`,`signature`,`type`,`toppings`, `isCoupon`)
VALUES
('$item','$type','$signature','0','0', '1')");
}
}
function removeMe(){
mysql_query("DELETE FROM `temp` WHERE `item`=21 AND
`signature`='".getSignature()."'");
}
}
You can achieve this something like this using functions without including file.
<?php
$readyTotal = $qty*price;
if($readyTotal > 1000) //considering amount in $
{
addItemToCart($cartDetails) // call function to add item into the cart
}
else {
removeItemFromCart($cartDetails) //call function to remove item from cart
}
?>
Define functions addItemToCart and removeItemFromCart to fire your queries.
I have codes that should be getting value from mysql database, I can get only one value but I have while loop so it can get value and output data separated with comma. But I only get one value and cannot get multiple value. the result should be like this, // End main PHP block. Data looks like this: [ [123456789, 20.9],[1234654321, 22.1] ] here is the code:
<?php
// connect to MySQL
mysql_connect('localhost','','') or die("Can't connect that way!");
#mysql_select_db('temperature1') or die("Unable to select a database called 'temperature'");
if(ISSET($_GET['t']) && (is_numeric($_GET['t'])) ){
// message from the Arduino
$temp = $_GET['t'];
$qry = "INSERT INTO tempArray(timing,temp) VALUES(".time().",'$temp')";
echo $qry;
mysql_query($qry);
mysql_close();
exit('200');
}
// no temp reading has been passed, lets show the chart.
$daysec = 60*60*24; //86,400
$daynow = time();
if(!$_GET['d'] || !is_numeric($_GET['d'])){
$dayoffset = 1;
} else {
$dayoffset = $_GET['d'];
}
$dlimit = $daynow-($daysec*$dayoffset);
$qryd = "SELECT id, timing, temp FROM tempArray WHERE timing>='$dlimit' ORDER BY id ASC LIMIT 1008";
// 1008 is a weeks worth of data,
// assuming 10 min intervals
$r = mysql_query($qryd);
$count = mysql_num_rows($r);
$i=0;
$r = mysql_query($qryd);
$count = mysql_num_rows($r);
while($row=mysql_fetch_array($r, MYSQL_ASSOC)) {
$tid=$row['id'];
$dt = ($row['timing']+36000)*1000;
$te = $row['temp'];
if($te>$maxtemp) $maxtemp=$te; // so the graph doesnt run along the top
if($te<$mintemp) $mintemp=$te; // or bottom of the axis
$return="[$dt, $te]";
echo $return; //here I get all values [1385435831000, 21][1385435862000, 23][1385435892000, 22][1385435923000, 25][1385435923000, 22]
$i++;
if($i<$count) $return= ","; echo $return; // if there is more data, add a ',' however, it return me ,,,[1385435923000, 22]
$latest = "$dt|$te"; // this will get filled up with each one
}
mysql_close();
// convert $latest to actual date - easier to do it here than in javascript (which I loathe)
$latest = explode('|',$latest);
$latest[0] = date('g:ia, j.m.Y',(($latest[0])/1000)-36000);
?>
You're just assigning $return to the values from the last row your while loop grabbed instead of concatenating it. Try this
$return = "[";
while($row=mysql_fetch_array($r, MYSQL_ASSOC)) {
$tid=$row['id'];
$dt = ($row['timing']+36000)*1000;
$te = $row['temp'];
if($te>$maxtemp) $maxtemp=$te; // so the graph doesnt run along the top
if($te<$mintemp) $mintemp=$te; // or bottom of the axis
$return.="[$dt, $te]";
$i++;
if($i<$count) $return .= ", ";// if there is more data, add a ','
$latest = "$dt|$te"; // this will get filled up with each one
}
$return .= "]";
I want to take a value from a query in one function and use it for multiplication within another function.
Here i have a function producing the number 3:
function insert() {
$siteid = 1;
$field = 3;
$time = "2011-10-11 15:04:56";
$this->db->select('Offset_value', 1)
->from('offset')
->where('siteid', $siteid)
->where('Offset_field', $field)
->where('time <', $time);
$query = $this->db->get()->result_array();
foreach ($query as $row) {
echo $row['Offset_value'];
}
return $query;
}
At the moment this is just set to display the number 3 but i need that value to be stored in a variable of some sort and load it into this function:
function get_sap_estimate() {
$kwp = 5;
$direction = 34;
$tilt = 60;
$month = 4;
$sap_shadingid = 2;
$this->db->select('derating_factor')
->from('sap_shading')
->where('id', $sap_shadingid);
$query = $this->db->get()->result_array();
$query = $query[0];
$dr = $query['derating_factor'];
$this->db->select("kwh * $dr * $kwp AS kwhdata")
->from('expected_kwh')
->where('direction', $direction)
->where('tilt', $tilt)
->where('month', $month);
$query2 = $this->db->get()->result_array();
return $query2;
}
Can this be done and how??
Thanks
function A(){
return "value";
}
functionB(){
var value = A(); // here is your array
var value_you_need = value[0]['Offset_value'];
}
If they are both in the same class (read: model file) write
var $_var;
before any methods are made. Then inside one of your methods type
$this->_var = $stuff;
to give this var a value. Then to use that value type
$new_stuff = $this->_var;
If they're not in the same class, you could try calling the first method inside of the second.
Here is my code for the function
function multiple_delete($checkbox, $table = 0, $url = 0, $picture1 = 0, $picture2 = 0, $picture3 = 0){
echo $count = count($checkbox);
for( $j=0;$j<$count;$j++)
{
$delete_id = $checkbox[$j];
$query = "SELECT * FROM $table WHERE id = '$delete_id'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if( $picture1 !== 0 && $picture2 !== 0 && $picture3 !== 0)
{
$pic_1 = $picture1;
$pic_2 = $picture2;
$pic_3 = $picture3;
unlink($pic_1);
unlink($pic_2);
unlink($pic_3);
continue;
}
if( $picture1 !== 0 && $picture2 !== 0 && $picture3 == 0 )
{
$pic_1 = $picture1;
$pic_2 = $picture2;
unlink($pic_1);
unlink($pic_2);
continue;
}
}
for($i=0;$i<$count;$i++) {
$del_id = $checkbox[$i];
$sql = "DELETE FROM $table WHERE id='$del_id'";
$result_delete_data = mysql_query($sql);
}
alert('Deleted Successfully');
redirect_url($url);
return true;
}
My Problem is when i call the function using the following code.
#multiple_delete($_POST['checkbox'], 'news', 'news.php', '$row[\'pic_title\']', '$row[\'pic_brief\']', '$row[\'pic_detail\']');
the three array variables $row['pic_title'], $row['pic_brief'], $row['pic_detail'] , does not parse as the value in the function in first for loop, instead it just print the string and hence is not able to fetch the value stored in the database. for example
in the first if condition i have defined 3 variables,
$pic_1 = $picture1;
$pic_2 = $picture2;
$pic_3 = $picture3;
$picture1, $picture2, and $picture3 holds the value that i declared in the function , now when i do something like this echo $pic_1 = $picture1; it prints $row['pic_title'] the exact value which i declared in the function instead of parsing the value which is actually upload/news/title/pic_title1.jpg i tried testing it like this, instead of declaring the value in the defined function i actually just changed the value of the three variables to
$pic_1 = $row['pic_title'];
$pic_2 = $row['pic_brief'];
$pic_3 = $row['pic_detail'];
this works very fine without any problem. why is that variable $picture1 which holds the value $row['pic_title']; refuses to parse it and force it to just print the string while if i change it manually it works? where i am going wrong?
apart from the last three parameters i dont have any problem parsing the first three parameters it works perfectly fine i have tested it in many ways. the only problem i am facing is of the last three parameters
Edit : i tried double quotes, single quotes, and single quotes with double quote with the combination of concatenation operator. without quotes. nothing works.
P.S : thanks in advance
Try this:
function multiple_delete($checkbox, $table, $url, $picture1, $picture2, $picture3){
echo $count = count($checkbox);
for($j=0; $j<$count; $j++)
{
$delete_id = $checkbox[$j];
$query = "SELECT * FROM $table WHERE id = '$delete_id'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$pic1 = $row[$picture1];
$pic2 = $row[$picture2];
$pic3 = $row[$picture3];
if(!empty($pic1) && !empty($pic2) && !empty($pic3))
{
unlink($pic1);
unlink($pic2);
unlink($pic3);
}
else if(!empty($pic1) && !empty($pic2))
{
unlink($pic1);
unlink($pic2);
}
$sql = "DELETE FROM $table WHERE id='$delete_id'";
$result_delete_data = mysql_query($sql);
}
// this is javascript, not php
// alert('Deleted Successfully');
redirect_url($url);
return true;
}
Call the function like this:
multiple_delete($_POST['checkbox_name'], 'table_name', 'redirect_url', 'column_name_pic_1', 'column_name_pic_2', 'column_name_pic_3');
get rid of the apostrophes around your variable names in the function call, ie try
, $row[\'pic_title\'],
instead of
, '$row[\'pic_title\']',
I got the solution for this problem. in case it can benefit anyone here is the link to the solution.
How do i parse the the value from a string in the function call?