How can I use sql data in header link? - sql

I need to use a variable from SQL. I can print which I wrote the variable. But I can't use
it when it out of while query.
Here is the SQL:
if ($result = $mysqli->query("SELECT * FROM organize WHERE organize.nid=$nid"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
while ($row = $result->fetch_object())
{
echo $row->nid;
echo $row->omid;
$id=$row->omid;
}
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
And the header under this scripts.
header("Refresh: 10;http://localhost/records.php?mid= $id ");
I know this is not right way. But I show you what I want. Need to use that 'omid' in header inseat of '$id'.

Finally I resolved it. This scripts like the above codes. I didn't understand why It didn't work. Maybe because I should not use
echo $row->nid;
echo $row->omid;
or
$id=$row->omid;
The right usage is as follows:
while ($row = $result->fetch_object())
{
$dd=$row->omid;
}
header("Refresh: 2;http://localhost/records.php?mid= $dd");

Related

Checking if update query affected rows perl

I have an "UPDATE" query and I want to check if this query has affected any rows and if it has I would like to send an email to myself. I'm not really experienced with perl or sql. (I'm using postgresql).
EDIT: I know that UPDATE returns "count" which tells how many rows if any have been updated, but I still don't know how to get to it.
The code looks like this:
my $updateQuery - //UPDATE query
if(//updateQuery has effected rows){
//send mail
}else
//do nothing
The problem is I don't know what to put into the if, what flag should I set? Is there any easy check that answers "has effected rows"?
Shortcut version using do()
my $update_query = '...';
my $ret = $dbh->do($update_query);
if ($ret) {
if ($ret eq '0E0') {
# no rows updated
} else {
# rows updated
}
} else {
# error
}
Full prepare()/execute() version.
my $update_query = '...';
my $sth = $dbh->prepare($update_query);
my $ret = $sth->execute;
if ($ret) {
if ($ret eq '0E0') {
# no rows updated
} else {
# rows updated
}
} else {
# error
}

mysqli inserts typed values but not variables

I have tried to get the following code to work. It is an ajax-call where I send a json-encoded string 'data':
<?php
require_once('connect.php'); // get values for mysqli-connect
$arr1 = json_decode($_GET['data']);
$arr = array_values($arr1);
if ($GLOBALS['TSFE']->loginUser) {
$mysqli = new mysqli($server,$user,$pw,$db);
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//values to be inserted in database table
$var1 = "Hello World";
$var2 = 45;
$var3 = "an encoded array";
/*
$var1 = $arr[1];
$var2 = $arr[2];
$var3 = json_encode($arr[3]);
*/
$insert_row = $mysqli->query("INSERT INTO table_testing
(event, pid, myarray) VALUES ('$var1', '$var2', '$var3')");
if($insert_row){
print 'Success! ID of last inserted record is : ' .$mysqli->insert_id .'<br />';
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
} else {
echo "User is NOT logged in!\n";
}
?>
My problem is that this code works! It works fine with the three values that are stored in $var1-3. They are saved in the correct table.
But - if I try to store the out-commented three values from $arr[1-3] into $var[1-3] it doesn't work? The three values saved are ' ' (empty), '0' and 'NULL'.
I have tried to put these lines in right after $arr is declared:
echo $arr[1]."\n";
echo $arr[2]."\n";
echo json_encode($arr[3])."\n";
In the console the correct values are printed, so they are valid and exist. It is a string, an integer and an array.
What is it I have overlooked or not understood?
Indexes of PHP arrays start are 0-based.
Try with this code:
echo $arr[0] . "\n";
echo $arr[1] . "\n";
echo json_encode($arr[2]) . "\n";

Phalcon: specific column on joined PHQL

The below PHQL generates a complex resultset like it should:
$phql = "SELECT User.*, ProductUser.* "
. "FROM ProductUser "
. "INNER JOIN User "
. "WHERE ProductUser.product_id = 5";
Replacing ProductUser.* with an existing column like ProductUser.id causes an error:
MESSAGE: The index does not exist in the row
FILE: phalcon/mvc/model/row.zep
LINE: 67
This is version 2.0.6. Is this a bug or am I making a mistake somewhere? According to the documentation it should be fine.
It was my mistake (expecting the row to always be an object).
I hope this helps someone because looping complex resultsets is not in the documentation.
$result = $this->modelsManager->createQuery($phql)->execute();
if ($result instanceof \Phalcon\Mvc\Model\Resultset\Complex) {
foreach ($result as $rows) {
foreach ($rows as $row) {
if (is_object($row)) {
$modelData = $row->toArray());
// this is what I needed
} else {
$id = $row;
}
}
}
}
First of all you're missing the ON clause in your query.
Anyways, it's easier and more error prone to use Phalcon's query builder for querying:
<?php
// modelManager is avaiable in the default DI
$queryBuilder = $this->modelsManager->createBuilder();
$queryBuilder->from(["product" => 'Path\To\ProductUser']);
// Inner join params are: the model class path, the condition for the 'ON' clause, and optionally an alias for the table
$queryBuilder->innerJoin('Path\To\User', "product.user_id = user.id", "user");
$queryBuilder->columns([
"product.*",
"user.*"
]);
$queryBuilder->where("product.id = 5");
// You can use this line to debug what was generated
// $generatedQuery = $queryBuilder->getPhql();
// var_dump($generatedQuery);
// Finish the query building
$query = $queryBuilder->getQuery();
// Execute it and get the results
$result = $query->execute();
// Now use var_dump to see how the result was fetched
var_dump($result);
exit;

Infinite scroll for sql items

I'm trying to a segment of code which is behaving strange.
I am using the Paul Irish infinite scroll with the JQuery masonry plugin to display content.
The content is pulled by sql and has a set number, currently 20.
This means the page will load the first 20 rows of content from the database, then will load the next 20 upon scrolling down.
I have this functionality on a few pages and it works fine except for one page.
On this page instead of loading the most recent 20 posts, it loads every post in that particular field. Some have over 5000 posts so it literally crashes the page. A major problem as you can imagine.
I have been trying to adapt the code to look for anomalies and have narrowed it down (I think) to one particular segment.
This is the code used on a page that works:
function index() {
$userID = false;
$order = false;
$limit = $this->config->item('pin_load_limit');
$page = $this->uri->segment(3, 1);
$nextOffset = ($page -1) * $limit;
$nextPage = $page +1;
$sql = "SELECT *
FROM
pins";
if ($userID)
$sql .= " WHERE
user_id= $userID ";
if ($order) {
$sql .= " ORDER BY
' $order'";
} else {
$sql .= " ORDER BY time DESC";
}
$sql .= " LIMIT $nextOffset,$limit";
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
$row = $query->result();
}
This is the code on the page that doesn't work:
function getEachBoardPins($id,$limit=false)
{
$sql = "SELECT
*
FROM
pins
WHERE
board_id = $id
ORDER BY time DESC";
if($limit)
$sql .=" LIMIT 0 ,$limit" ;
$query = $this->db->query($sql);
return $query->result();
}
I know it is to do with the pin load limit but I have tried adding the code to the latter without success.
Perhaps somebody on here who knows more about it can provide some better insight?
I imagine that it is VERY LIKELY that when you call the "getEachBoardPins" function, you aren't setting the second parameter, hence, it is defaulting to false, hence, the limit SQL isn't being appended, so the select statement will run the whole statement.

Magento - Module INSERT,UPDATE, DELETE, SELECT code

I created a module and want to used core write and read function to insert,update,delete or select database value with condition, how can I do it without using SQL?
Example:
$customer_id=123
Model=(referral/referral)
SELECT
$collection3 = Mage::getModel('referral/referral')->getCollection();
$collection3->addFieldToFilter('customer_id', array('eq' => $customer_id));
foreach($collection3 as $data1)
{
$ref_cust_id.= $data1->getData('referral_customer_id');
}
INSERT
$collection1= Mage::getModel('referral/referral');
$collection1->setData('customer_id',$customer_id)->save();
DELETE,UPDATE(with condition)=???
Suppose, I have a module named mynews.
Here follows the code to select, insert, update, and delete data from the news table.
INSERT DATA
$data contains array of data to be inserted. The key of the array should be the database table’s field name and the value should be the value to be inserted.
$data = array('title'=>'hello there','content'=>'how are you? i am fine over here.','status'=>1);
$model = Mage::getModel('mynews/mynews')->setData($data);
try {
$insertId = $model->save()->getId();
echo "Data successfully inserted. Insert ID: ".$insertId;
} catch (Exception $e){
echo $e->getMessage();
}
SELECT DATA
$item->getData() prints array of data from ‘news’ table.
$item->getTitle() prints the only the title field.
Similarly, to print content, we need to write $item->getContent().
$model = Mage::getModel('mynews/mynews');
$collection = $model->getCollection();
foreach($collection as $item){
print_r($item->getData());
print_r($item->getTitle());
}
UPDATE DATA
$id is the database table row id to be updated.
$data contains array of data to be updated. The key of the array should be the database table’s field name and the value should be the value to be updated.
// $id = $this->getRequest()->getParam('id');
$id = 2;
$data = array('title'=>'hello test','content'=>'test how are you?','status'=>0);
$model = Mage::getModel('mynews/mynews')->load($id)->addData($data);
try {
$model->setId($id)->save();
echo "Data updated successfully.";
} catch (Exception $e){
echo $e->getMessage();
}
DELETE DATA
$id is the database table row id to be deleted.
// $id = $this->getRequest()->getParam('id');
$id = 3;
$model = Mage::getModel('mynews/mynews');
try {
$model->setId($id)->delete();
echo "Data deleted successfully.";
} catch (Exception $e){
echo $e->getMessage();
}
In this way you can perform select, insert, update and delete in your custom module and in any magento code.
Source: http://blog.chapagain.com.np/magento-how-to-select-insert-update-and-delete-data/
UPDATE is basically the combination of SELECT and INSERT. You load a collection, iterate over them setting the values as needed, then call ->save() on each model.
DELETE is handled directly via the ->delete() functon of models. So either load a single model or iterate over a SELECTed collection of them and call ->delete()
(Not that due to the iteration, this is not the 'fastest' way of doing these operations on collections (because each one is going to generate a new query, instead of a single query that handles multiple deletes at once), but the performance is fine for either small data sets/SELECTs (less than 1k?) or for things that you don't do very often (like importing or updating prices ok 10k products once per day).
FOR UPDATE
$new=$this->getRequest()->getParams();
$id=$new['id'];
$name=$new['name'];
$con=Mage::getModel('plugin/plugin')->load($id);
$con->setData('name',$name)->save();
echo "Update Success";
FOR DELETE
$id = $this->getRequest()->getParam('id');
$model = Mage::getModel('plugin/plugin');
$model->setId($id)->delete();
echo "Data deleted successfully.";
You can use select query like this also. its very easy.
$salesInvoiceCollection_sql = "SELECT `entity_id` , `increment_id`,`order_id`
FROM `sales_flat_invoice`
WHERE `erp_invoice_id` = 0
ORDER BY `entity_id`
DESC limit 1000";
$salesInvoiceCollection = Mage::getSingleton('core/resource')->getConnection('core_read')->fetchAll($salesInvoiceCollection_sql);
If you want to delete with condition based on collection you can use addFieldToFilter, addAttributeToFilter
$model = Mage::getModel('mynews/mynews')->getCollection();
try {
$model->addAttributeToFilter('status', array('eq' => 1));
$model->walk('delete');
echo "Data deleted successfully.";
} catch (Exception $e){
echo $e->getMessage();
}