Bit of a noob when it comes to PDO. We have a a table that needs to be updated with a cron job daily. The idea is to query the table and for each "active = 1" get an integer from a duration column convert that into days, get the "expiration" column and the duration to the expiration and update the expiration.
I am not even close to getting this to work, I am trying to just get the basics for now. Return the duration which is in hours divide by 24 add that to the date column as days and update EACH row with the appropriate new time.
The problem is I do not know how to update each row with its own information. I have the code below, it updates each row but the new "expires" date ends up being the same even though the expires values are different.
static function cronSetFeatured(){
try{
$db = new PDO('mysql:host=127.0.0.1;dbname=mydb', 'dbuser', 'pw' );
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo $e->getMessage();
die();
}
$query = $db->query('SELECT * FROM featured_producers ');
$now = date('Y-m-d H:i:s');
while($r = $query->fetch(PDO::FETCH_OBJ)){
$duration = $r->duration;
$ddays = $duration / 24;
$date = $r->date;
$expires = date("Y-m-d", strtotime($date. " + ".$ddays." days"));
}
$sql = "UPDATE `featured_producers`
SET `expires`= ?
WHERE `id` != 0";
$q = $db->prepare($sql);
$q->execute(array($expires));
echo $expires.'<br>';
}
Well if you want to UPDATE each record on its own, that query need to be part of the loop body:
while($r = $query->fetch(PDO::FETCH_OBJ)){
//calculate expiration
$duration = $r->duration;
$ddays = $duration / 24;
$date = $r->date;
$expires = date("Y-m-d", strtotime($date. " + ".$ddays." days"));
//Get the id (needed for update)
$id = $r->id;
//updating
$sql = "UPDATE `featured_producers`
SET `expires`= ?
WHERE `id` != ?";
$q = $db->prepare($sql);
$q->execute(array($expires, $id));
echo $expires.'<br>';
}
Related
I am currently having problem getting the number of rows in my code. here's my code:
$app->get('/banana/:state', function($state) use ($app){
$db = new DbOperation();
$today = date("j-M-Y");
if($state == "Indoor"){
$result = $db->getAllbananaindoor($today);
$response = array();
$response['messages'] = array();
$row = $result->fetch_assoc();
if($row > 3){
$temp = array();
$temp['text'] = 'Yes, you can plant banana seeds today indoors.';
array_push($response['messages'],$temp);
}
else {
$temp = array();
$temp['text'] = 'Nope. Today is not a good time to plant banana seeds indoors.';
array_push($response['messages'],$temp);
}
echoResponse(200,$response);
}
}
public function getAllbananaindoor($today){
$stmt = $this->con->prepare("SELECT * FROM garden WHERE humid >? AND time=? AND temp BETWEEN ? AND ?");
$hum = '50';
$one = '19';
$two = '24';
$stmt->bind_param("iiii",$hum, $today, $one, $two);
$stmt->execute();
$students = $stmt->get_result();
$stmt->close();
return $students;
}
In this I get the database data from a function getAllBananaindoor() which returns the result instead i want it return the number of rows and finally check whether $row is greater than 3 and then work on that. how can I do that? please help.
The MySQLi Result object has num_rows property defined.
$students = $stmt->get_result();
return $students->num_rows; // will return the number of rows
I have done this type of SELECT many times, but this time I can't get it to work. Any ideas, please?
$Name = "Dick";
$conn = mysqli_connect($server, $dbname, $dbpw, $dbuser);
$sql = "SELECT id FROM table WHERE $Name = table.first_name";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$customer_id = $row['id'];
Database::disconnect();
echo "customer id = " . $customer_id;
If you really DO have a table named table it would be more appropriate to use back ticks around the name since the word TABLE is a reserved word in MySQL. You should also use single quotes around your variable if it contains a string:
$sql = "SELECT `id` FROM `table` WHERE `first_name` = '$Name'";
Other possible reasons if the query still doesn't work for you:
Make sure you have the connection parameters in the right order. It should be: mysqli_connect($server, $dbuser, $dbpw, $dbname).
You should be using fetch_array() instead of fetch_assoc() if you expect a one row result.
You are mixing PROCEDURAL STYLE with Object Oriented Style when using mysqli_connect() instead of mysqli(), at the same time using $result-> which is object oriented style. You should decide one style and stick with it.
This would be the procedural style of your query:
$Name = "Dick";
$conn = mysqli_connect($server, $dbuser, $dbpw, $dbname); // NOTE THE CHANGED ORDER OF CONNECTION PARAMETERS!
$sql = "SELECT `id` FROM `table` WHERE `first_name` = '$Name'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$customer_id = $row['id']; // YOUR CUSTOMER ID
mysqli_free_result($result); // FREE RESULT SET
mysqli_close($conn); // CLOSE CONNECTION
And this would be the object oriented style:
$Name = "Dick";
$conn = new mysqli($server, $dbuser, $dbpw, $dbname);
$sql = "SELECT `id` FROM `table` WHERE `first_name` = '$Name'";
$result = $conn->query($sql);
$row = $result->fetch_array(MYSQLI_ASSOC);
$customer_id = $row['id']; // YOUR CUSTOMER ID
$result->free(); // FREE RESULT SET
$conn->close(); // CLOSE CONNECTION
I would recommend naming your table something else than table since it's a reserved word and could get you into parsing problems. The same goes with field names. More reading: https://dev.mysql.com/doc/refman/5.5/en/keywords.html
More about mysqli_fetch_array() and differences in procedural style and object oriented style use: http://php.net/manual/en/mysqli-result.fetch-array.php
$sql = "SELECT id FROM table WHERE '$Name' = table.first_name";
You simply need to concat the variable like this:
$sql = "SELECT id FROM table WHERE " . $Name . " = table.first_name";
I started my project March last year and have almost got it right.
Trying to get data from mysql and put it in highcharts.
This is my query
<?php
$con = mysqli_connect("localhost","root","root","manortsc_test");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
$sth = mysqli_query($con,"
SELECT DateTime,max(T)
FROM alldata
WHERE DATE(DateTime) = CURDATE() - INTERVAL 1 DAY
GROUP BY hour(DateTime)
"
);
$rows = array();
$rows['name'] = 'Outside';
while($r = mysqli_fetch_array($sth)) {
$rows['data'][] = $r['max(T)'];
}
$result = array();
array_push($result,$rows);
print json_encode($result, JSON_NUMERIC_CHECK);
mysqli_close($con);
?>
The json output is missing the date and time
[{"name":"Outside","data":[17.5,16.3,15.6,15.1,14.4,14,14.1,16,18.5,21.7,24.1,26.9,28.3,29.6,30.6,31.1,31.8]}]
The graph shows okay (except datetime on x axis) and I cannot figure how to fix it. I have tried every way except the correct way. Any help would be appreciated.
Changed the query to this and now it works.
Thanks wergeld and Yuri for the assistance.
$sth = mysqli_query($con,"
SELECT DateTime,max(T)
FROM davisvp
WHERE DATE(DateTime) = CURDATE()
GROUP BY hour(DateTime)
"
);
$result = array();
$result['name'] = 'temperature';
while($row = mysqli_fetch_array($sth))
{
$date = strtotime($row['DateTime']);
$maxt = 1 * $row['max(T)'];
$result1 = array();
array_push($result1,$date);
array_push($result1,$maxt);
$result['data'][] = $result1;
}
echo json_encode($result, JSON_NUMERIC_CHECK);
I am having a weird issue but I do not understand what is happening. I amcreated a function to update up to three columns (end_plan_date, balance and server) in a table (user) and 2 inserts in another table.
For some reason, my last update (column server of the user table) is not committed ($query = mysql_query("UPDATE user SET server='$serv' WHERE email='$subemail'");) unless I give a value for at leat one of the two other values ($subamt or $subday).
Do you know why this query is not updating the user table with the server value I parsed?
function addBalance($subemail, $subamt,$subday,$userid,$serv) {
$q = "SELECT * FROM user WHERE email = '$subemail'";
$result = mysql_query($q, $this->connection);
$dbarray = mysql_fetch_array($result);
$endplan_date=$dbarray['end_plan_date'];
if($subday >0){
if($endplan_date=="0000-00-00" ){
$endplan_date = date('Y-m-d');
$new_endplan_date = date('Y-m-d',strtotime($endplan_date . "+".$subday." days"));
}else{
$new_endplan_date = date('Y-m-d',strtotime($endplan_date . "+".$subday." days"));
}
$query = mysql_query("UPDATE user SET end_plan_date='$new_endplan_date' WHERE email='$subemail'");
$recdate=gmdate('Y-m-d H:i:s');
$q = "INSERT INTO com_gest(recdate,userid,type,recvalue) VALUES ('$recdate','$userid','Plan Date','$subday')";
mysql_query($q, $this->connection);
}
if($subamt >0){
$query = mysql_query("UPDATE user SET balance=balance+".$subamt." WHERE email='$subemail'");
$recdate=gmdate('Y-m-d H:i:s');
$q = "INSERT INTO com_gest(recdate,userid,type,recvalue) VALUES '$recdate','$userid','Balance','$subamt')";
mysql_query($q, $this->connection);
}
$query = mysql_query("UPDATE user SET server='$serv' WHERE email='$subemail'");
return 0;
}
In your code u can't get directly this
$endplan_date=$dbarray['end_plan_date'];
for fetching this variable u have to use while loop like
while($dbarray = mysql_fetch_array($result);) {
$endplan_date=$dbarray['end_plan_date'];
}
There was an issue when calling this function.
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 :)