_REQUEST only returning the first letter of input - number-theory

I am trying to update records in a database through a form (post), but when I access the global parameter variables, only the first character of the original input is returned for some reason.
$conn->beginTransaction();
$sql = "UPDATE AS_PEOPLE SET pid=? WHERE name=?";
$stmt = $conn->prepare($sql);
$values = Array($_REQUEST['project'][0], $_REQUEST['person'][0]);
$stmt->execute($values);
$conn->commit();
echo "Ressource allocated<br>";
print_r($values);

Your problem is here
$values = Array($_REQUEST['project'][0], $_REQUEST['person'][0]);
$_REQUEST['project'] and $_REQUEST['person'] are strings, containing values of selected option. If you tell php to get the index of 0 of a string it returns the first letter only
$values = Array($_REQUEST['project'], $_REQUEST['person']);

Related

Update a database field with Joomla UpdateObject method with a calculated field from same table

Right to the point.
I need to update a field in the database using the field to calculate the new value first.
E.g of fields: https://i.stack.imgur.com/FADH6.jpg
Now I am using the Joomla updateObject function. my goal is to take the "spent" value from the DB table without using a select statement.
Then I need to calculate a new value with it like (spent + 10.00) and update the field with the new value. Check out the code below:
// Create an object for the record we are going to update.
$object = new stdClass();
// Must be a valid primary key value.
$object->catid = $item['category'];
$object->spent = ($object->spent - $item['total']);
// Update their details in the users table using id as the primary key.
$result = JFactory::getDbo()->updateObject('#__mytable', $object, 'catid');
The bit which i need to make the calculation on is
$object->spent = ($object->spent - $item['total']);
I realise I can use a seperate insert statement but I am wondering if there is a better way. Any help is much appreciated.
It needs to work like this, WITHOUT THE SELECT (working example)
$query = $db->getQuery(true);
$query->select($db->quoteName('spent'));
$query->from($db->quoteName('#__mytable'));
$query->where($db->quoteName('catid')." = ". $item['category']);
// Reset the query using our newly populated query object.
$db->setQuery($query);
$oldspent = $db->loadResult();
// Create an object for the record we are going to update.
$object = new stdClass();
// Must be a valid primary key value.
$object->catid = $item['category'];
$object->spent = ($oldspent - $item['total']);
// Update their details in the users table using id as the primary key.
$result = JFactory::getDbo()->updateObject('#__mytable', $object, 'catid');
The sticking point with trying to use updateObject('#__mytable', $object, 'catid'); is that your query logic needs to reference the column name in the calculation to assign the "difference" as the new value. The raw mysql query syntax to update a column value with the value minus another value is like:
"`spent` = `spent` - {$item['total']}"
updateObject() will convert spent - {$item['total']} to a literal string, the database will expect a numeric value, so UPDATE results in a 0 value recorded. In other words, $db->getAffectedRows() will give you a positive count and there will be no errors generated, but you don't get the desired mathematical action.
The workaround is to discard updateObject() as a tool and build an UPDATE query without objects -- don't worry it's not too convoluted. I'll build in some diagnostics and failure checking, but you can remove whatever parts that you wish.
I have tested the following code to be successful on my localhost:
$db = JFactory::getDBO();
try {
$query = $db->getQuery(true)
->update($db->quoteName('#__mytable'))
->set($db->quoteName("price") . " = " . $db->qn("price") . " - " . (int)$item['total'])
->where($db->quoteName("catid") . " = " . (int)$item['category']);
echo $query->dump(); // see the generated query (but don't show to public)
$db->setQuery($query);
$db->execute();
if ($affrows = $db->getAffectedRows()) {
JFactory::getApplication()->enqueueMessage("Updated. Affected Rows: $affrows", 'success');
} else {
JFactory::getApplication()->enqueueMessage("Logic Error", 'error');
}
} catch (Exception $e) {
JFactory::getApplication()->enqueueMessage("Query Syntax Error: " . $e->getMessage(), 'error'); // never show getMessage() to public
}
Here is a StackOverflow page discussing the mysql subtraction logic: update a column by subtracting a value

Code Igniter - remove single quotes from where_in

I have 2 queries:
$genres = $this->db->select('Group_Concat(intGenreId) strDJGenres')
->from('tblDJGenres')
->where('intDJId', $this->session->userdata('non_admin_userid'))
->get()
->row();
$results = $this->db->select('tblTracks.*, tblGenres.strName as strGenreName')
->from('tblTracks')
->join('tblGenres', 'tblTracks.intGenreId = tblGenres.intGenreId', 'left')
->where_in('tblTracks.intGenreId', $genres->strDJGenres)
->get()
->result();
The first query is returning a string such as
'1,2,3,4,8,6,5,7,45,66'
which I am using in my where_in clause on the second query. The issue is that with this string, it is writing the SQL like:
SELECT `tblTracks`.*, `tblGenres`.`strName` as strGenreName FROM (`tblTracks`) LEFT JOIN `tblGenres` ON `tblTracks`.`intGenreId` = `tblGenres`.`intGenreId` WHERE `tblTracks`.`intGenreId` IN ('1,2,3,4,8,6,5,7,45,66')
With the quote around it, it is treated as a single value. How can I get the second query to perform how I want it? ie
.... where `tblTracks`.`intGenreId` IN (1,2,3,4,8,6,5,7,45,66)
Multiple values can be passed to the where_in clause as an array.
The quotes from the start and end of the string can be removed using trim():
$dj_genres = trim($genres->strDJGenres, "'");
This string can then be converted into an array of strings, to pass to the where_in clause of the second query.
$dj_genres_array = explode(",", $dj_genres);
Or, if you need an array of integers:
$dj_genres_int_array = array_map('intval', $dj_genres_array);
You can just add the resultant array into the second query:
// ...
->where_in('tblTracks.intGenreId', $dj_genres_array)
// ...
Or:
// ...
->where_in('tblTracks.intGenreId', $dj_genres_int_array)
// ...
Answer given by the JLeft :
The quotes from the start and end of the string can be removed using the following function:
$dj_genres = trim($genres->strDJGenres, "'");
This string can then be converted into a array of strings, to pass to the where_in clause of the second query.
$dj_genres_array = explode(",", $dj_genres);
If you need an array on integers, it can be generated as so:
$dj_genres_int_array = array_map('intval', $dj_genres_array);
was working absolutely fine...Thanks JLeft

Codeigniter Active Record return type

I tried to get a umat_id with this SQL query :
SELECT umat_id FROM msumat WHERE nama = $nama
I converted this SQL query into CI's Active Record :
$this->db->select('umat_id');
$terdaftar = $this->db->get_where('msumat', array('nama' => $nama));
So this query should return a string (example : "John").
But I got an error when I tried to echo it :
Object of class CI_DB_mysql_result could not be converted to string
I have tried something like this : echo (string)$terdaftar;, but it's not working.
All I want is to echo "John"
EDIT
Just said I want to insert "John" into a variable. How to do that?
$john = ????
As some of the users already pointed the solution, I'm only explaining why you did get this error so you can understand better the querying results that codeigniter gives.
This error:
But I got an error when I tried to echo it : Object of class
CI_DB_mysql_result could not be converted to string
Happens because you were trying to echo an object.
This piece of code
$terdaftar = $this->db->get_where('msumat', array('nama' => $nama));
Will return an object, this object will have information about the query you've done.
With this object you can get the result(rows) as objects doing this:
$results = $terdaftar->result();
Or you if you feel more comfortable with arrays you can return the results(rows) as an array doing this:
$results = $terdaftar->result_array();
You can also get the number of results doing this:
$number_results = $terdaftar->num_rows()
And this is just an example you can read more about the results here
http://ellislab.com/codeigniter/user-guide/database/results.html
EDIT
A better explanation: imagine that we use the result_array() function to get the result in a pure array format:
$results = $terdaftar->result_array();
Now your variable $results is an array, to iterate through it and get the data you want you'll do something like this:
foreach ($results as $key => $row) {
//the row variable will have each row of your database returned by your query
//so if you want to access a field from that row,
//let's say for example the name field. You would do something like this
if($row['name']=='John')
echo $row['name'];
}
Try:
$this->db->select('umat_id');
$terdaftar = $this->db->get_where('msumat', array('nama' => $nama));
foreach ($terdaftar->result() as $row)
{
echo $row->umat_id;
}
Read the documentation for more information.
Try this:
$this->db->select('umat_id');
$terdaftar = $this->db->get_where('msumat', array('nama' => $nama));
$row = $terdaftar->row_array();
$your_variable = $row['umat_id']; /*Here comes your john*/

Vtiger select query

I'm copying a vtiger query in a similar way but there is one change that the query given first having only one output so there is kept 0 in 2nd argument,
but in my customized query there are multiple outputs so what should I kept instead of 0
both are given as below:
original query
$is_recurring_event_query = $adb->pquery('SELECT recurring_group_id from vtiger_activity where activityid=?',array($id));
$is_recurring_event = $adb->query_result($is_recurring_event_query,0,'recurring_group_id');
copying it to use at different way
$is_recurring_event_activity_query = $adb->pquery('SELECT activityid from vtiger_activity where recurring_group_id='.$is_recurring_event);
$is_recurring_event_activity = $adb->query_result ($is_recurring_event_activity_query,0,'activityid');
You have to put variable and have to use for loop for your query to execute and get multiple values.
Suppose your query is like this
$result = $adb->pquery ('SELECT * from vtiger_activity where id='.$recordId);
$noofrow = $adb->num_rows($result );
for($i=0; $i<$noofrow ; $i++) {
$Data['activityid']=$adb->query_result($result,$i,'activityid');
$Data['activityname']=$adb->query_result($result,$i,'activityname');
}
Here in $Data you will get an array of the values.

How do I select a single row in Magento in a custom database for display in a block?

I don't want to use foreach to loop through an array of multiple rows, as I am planning on only displaying only one row and using a variable. I can't find information for this online.
What doesn't work
$param = $this->getRequest()->getParam('manufacturer');
$extrabrand = Mage::getModel('brands/brands')->getCollection();
$extrabrand->addFieldToFilter('attributelabelid', $param);
//$extrabrand->setAttributelabelid($param);
$extrabrand->load();
Fatal error: Call to undefined method
Desbest_Brands_Model_Mysql4_Brands_Collection::getDescription() in
/home/desbest/public_html/clients/magentofull/app/design/frontend/default/default/template/Desbest_Brands/brand_info.phtml
on line 20
Plus there is no EAV.
Without seeing the code in brand_info.phtml it's hard to say what the problem is, but my guess is you're using the collection in $extrabrand as though it were a model. Try this instead
//get the parameter from the request
$param = $this->getRequest()->getParam('manufacturer');
//instantiate the brand/brand model, and use
//its `getCollection` method to return a collection
//object
$collection = Mage::getModel('brands/brands')->getCollection();
//add the paramater as a filter
$collection->addFieldToFilter('attributelabelid', $param);
//get the first item of the collection (load will be called automatically)
$extrabrand = $collection->getFirstItem();
//look at the data in the first item
var_dump($extrabrand->getData());
If you need to get only 1 element (first) from the collection, use current() function:
$param = $this->getRequest()->getParam('manufacturer');
$extrabrandCollection = Mage::getModel('brands/brands')->getCollection()
->addFieldToFilter('attributelabelid', $param);
$extrabrand = current($extrabrandCollection->getItems());

Resources