PDO: UPDATE not working - php

I wrote some code to update a mySQL table via php/PDO.
But it is not working and I just can't figure out where my mistake is.
The execute() returns true, but the changes never actually show up in the table.
My code looks pretty much like this:
$columnObject = array(
"emailAddress"=>"aaa#aaa.com",
"passwordHash"=>"56bj5g63j4g57g567g5k75jh7gk4g74j5hg67",
"name"=>"qweqweqwe",
"lastActivity"=>4128649814
);
$knownColumnName = "emailAddress";
$knownColumnData = "aaa#aaa.com";
foreach ($columnObject as $columnName => $columnData) {
$pdoUpdateString .= $columnName . "=:" . $columnName . ",";
$pdoExecuteObject[$columnName] = $columnData;
}
$pdoUpdateString = rtrim($pdoUpdateString, ",");
$pdoExecuteObject['knownColumn'] = $knownColumnData;
$q = $this->hCon->prepare('UPDATE ' . $this->name . ' SET ' . $pdoUpdateString . ' WHERE ' . $knownColumnName . '=:knownColumn');
$q->execute($pdoExecuteObject);

Related

Problem fetching data from table using foreach loop

I am having problem in fetching data from database table, after loading data into array and loop using foreach it return blank instead of the values. I have tried using this way $row[''] it works fine but i want to use this operand -> but its fetching bank data.
$query = "SELECT * FROM pages_words";
$select_posts = mysqli_query($connection, $query);
$rows[] = array();
while ($row = mysqli_fetch_assoc($select_posts))
$rows[] = $row;
foreach ($rows as $key => $row) {
$idpw = $row['idpw'];
$pages = $row['pages'];
$words = $row['words'];
$amount_added = $row['amount_added'];
$page_type = $row['page_type'];
if ($page_type == 'double') {
if ($row->idpw == $post['no_of_pages']) {
echo '<option selected="selected" id="' . $row->idpw . 'nop" value="' . $row->idpw . '" title="' . $row->amount_added . '"> ' . $row->pages . ' Page(s) / ' . $row->words . ' Words</option>';
} else {
echo '<option id="' . $row->idpw . 'nop" value="' . $row->idpw . '" title="' .
$row->amount_added . '"> ' . $row->pages . ' Page(s) / ' . $row->words . ' Words</option>';
}
}
}
?>
blank data
kindly help solve the problem
You used mysqli_fetch_assoc(), which fetches rows as associative arrays. In other places in the foreach loop, you're accessing the row correctly using array syntax, such as $idpw = $row['idpw'];. You can't access array values using object syntax. Instead of using $row->idpw when outputting the option, you could either use $row['idpw'] or just use the $idpw variable you created earlier.
If you want the arrow operator to work, you'll need to use mysqli_fetch_object() instead, but if you do that you'll need to change the places where you're using array syntax to use object syntax as well.

Wrong Foreach cycle

i am doing something wrong with my foreach cycle. But looks my knowledge is not enugh to figure out what's wrong. My code is pretty simple:
$xnl_file = "xml.xml";
$xml = simplexml_load_file($xnl_file);
$my_file = 0;
foreach ($xml as $value){
var_dump($value);
$CountryOrganizationId = "<CountryOrganizationId>".$xml->Partnership->CountryOrganizationId."</CountryOrganizationId>";
$PartnershipId = "<PartnershipId>".$xml->Partnership->PartnershipId."</PartnershipId>";
$OwnerId = "<OwnerId>".$xml->Partnership->OwnerId."<OwnerId>";
$PartnerIdList = "<PartnerIdList><String>".$xml->Partnership->PartnerIdList->String."</String></PartnerIdList>";
$CountryOrganizationId_contact = "<Contract><CountryOrganizationId>".$xml->Partnership->Contract->CountryOrganizationId."</CountryOrganizationId>";
$ContractId = "<ContractId>".$xml->Partnership->Contract->ContractId."</ContractId>";
$data = "<Partnership>".$CountryOrganizationId.$PartnershipId.$OwnerId.$PartnerIdList.$CountryOrganizationId_contact.$ContractId.$Role1.$Category1.$Rate1.
$Role2.$Category2.$Rate2.$Role3.$Category3.$Rate3."</Partnership>";
echo $data;
}
I am getting data from XML and try to parse it on multiple one, but this just copy same data again and again. I am not sure what i am doing wrong. In my opinion data should rewrite each other every time cycle is doing same but they are not changing. At echo $data i get as many results as i should, problem is just they are same.
If I var_dump $value at start i get nice result that data are coming to cycle but why the output is the same all the time?
Please can somebody give me advise?
Thanks
The $value variable is never used, you're always using the $xml. Try it like:
$xnl_file = "xml.xml";
$xml = simplexml_load_file($xnl_file);
$my_file = 0;
foreach ($xml as $value){
var_dump($value);
$CountryOrganizationId = "<CountryOrganizationId>" . $value->CountryOrganizationId . "</CountryOrganizationId>";
$PartnershipId = "<PartnershipId>" . $value->PartnershipId . "</PartnershipId>";
$OwnerId = "<OwnerId>" . $value->OwnerId . "<OwnerId>";
$PartnerIdList = "<PartnerIdList><String>" . $value->PartnerIdList->String . "</String></PartnerIdList>";
$CountryOrganizationId_contact = "<Contract><CountryOrganizationId>" . $value->Contract->CountryOrganizationId . "</CountryOrganizationId>";
$ContractId = "<ContractId>" . $value->Contract->ContractId . "</ContractId>";
$data = "<Partnership>" . $CountryOrganizationId . $PartnershipId . $OwnerId . $PartnerIdList . $CountryOrganizationId_contact .
$ContractId . $Role1 . $Category1 . $Rate1 . $Role2 . $Category2 . $Rate2 . $Role3 . $Category3 . $Rate3 .
"</Partnership>"afdsf
echo $data;
}
Concat $data to its previous value { $data .= "......"}
foreach ($xml as $value)
{
var_dump($value);
$CountryOrganizationId = "<CountryOrganizationId>".$xml->Partnership->CountryOrganizationId."</CountryOrganizationId>";
$PartnershipId = "<PartnershipId>".$xml->Partnership->PartnershipId."</PartnershipId>";
$OwnerId = "<OwnerId>".$xml->Partnership->OwnerId."<OwnerId>";
$PartnerIdList = "<PartnerIdList><String>".$xml->Partnership->PartnerIdList->String."</String></PartnerIdList>";
$CountryOrganizationId_contact = "<Contract><CountryOrganizationId>".$xml->Partnership->Contract->CountryOrganizationId."</CountryOrganizationId>";
$ContractId = "<ContractId>".$xml->Partnership->Contract->ContractId."</ContractId>";
$data .= "<Partnership>".$CountryOrganizationId.$PartnershipId.$OwnerId.$PartnerIdList.$CountryOrganizationId_contact.$ContractId.$Role1.$Category1.$Rate1.
$Role2.$Category2.$Rate2.$Role3.$Category3.$Rate3."</Partnership>";
}
echo $data;

How to get rid of empty values when adding string in php

I have something like this:
public function options()
{
$out = '';
$docs = $this->getAll();;
foreach($docs as $key => $doc) {
$out .= ',{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
}
return $out;
}
It gives me a list of options from the DB, but it also gives me a null value at the top.
if I write it like this:
public function options()
{
//$out = '';
$docs = $this->getAll();;
foreach($docs as $key => $doc) {
$out = '';
$out .= '{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
}
return $out;
}
It doesn't give me the null value but it only returns one value.
$out .= ',{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
In this line if I don't add an , it gives me an error message, This because I have $out = ''; at the top. Now can you guys give me an idea how can I get all the values from the DB without the empty value at the beginning.
I also have another question , why we use ;; (double semicolon) in this code:
$docs = $this->getAll();;
test $out to see if it has any length, if so add the comma and the line, otherwise just set it to be the line:
$out="";
foreach($docs as $key=>$doc){
if(strlen($out)){
$out.=',{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
}else{
$out='{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
}
}
as to your other question, er, you wrote the code, so why did you put a double semi-colon?
This is not the correct way to build JSON. First create an array, and use json_encode() on it.
I'd suggest using an array instead to hold the individual values, and using join to concatenate them together.
public function options()
{
$docs = $this->getAll();
// Create an empty array
$items = array();
foreach($docs as $key => $doc) {
// "Push" an item to the end of the array
$items[] = '{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
}
// Join the contents together
$out = join(",", $items);
return $out;
}
Also, the double semi-colon is completely unnecessary.

I need to remove duplicates from an array from a specific code

I have the following code:
public function ajax()
{
// Contains results
$data = array();
if( isset($this->request->get['keyword']) ) {
// Parse all keywords to lowercase
$keywords = strtolower( $this->request->get['keyword'] );
// Perform search only if we have some keywords
if( strlen($keywords) >= 3 ) {
$parts = explode( ' ', $keywords );
$add = '';
// Generating search
foreach( $parts as $part ) {
$add .= ' AND (LOWER(pd.name) LIKE "%' . $this->db->escape($part) . '%"';
$add .= ' OR LOWER(p.model) LIKE "%' . $this->db->escape($part) . '%")';
}
$add = substr( $add, 4 );
$sql = 'SELECT pd.product_id, pd.name, p.model FROM ' . DB_PREFIX . 'product_description AS pd ';
$sql .= 'LEFT JOIN ' . DB_PREFIX . 'product AS p ON p.product_id = pd.product_id ';
$sql .= 'LEFT JOIN ' . DB_PREFIX . 'product_to_store AS p2s ON p2s.product_id = pd.product_id ';
$sql .= 'WHERE ' . $add . ' AND p.status = 1 ';
$sql .= ' AND p2s.store_id = ' . (int)$this->config->get('config_store_id');
$sql .= ' ORDER BY LOWER(pd.name) ASC, LOWER(p.model) ASC';
$sql .= ' LIMIT 15';
$res = $this->db->query( $sql );
if( $res ) {
$data = ( isset($res->rows) ) ? $res->rows : $res->row;
// For the seo url stuff
$basehref = 'product/product&keyword=' . $this->request->get['keyword'] . '&product_id=';
foreach( $data as $key => $values ) {
$data[$key] = array(
'name' => htmlspecialchars_decode($values['name'] . ' (' . $values['model'] . ')', ENT_QUOTES),
'href' => $this->url->link($basehref . $values['product_id'])
);
}
}
}
}
echo json_encode( $data );
}
So, the array generates a list of products, like for e.g.:
Apple MacBook (Product Model 10)
Apple МакБук (Product Model 10)
The problem is that those two products is actually one and the same product (same product_id) but in different languages, and both have the same URL.
So, what I want to check is, while making the array, the code to check if there is already a product with that product_id in the array, and if there is, not to add another one with the same product_id.
Practically, I don't want the array to generate two or more products with the same product_id.
EDIT: With Marc's code and ghbarratt suggestion work like a charm. A million thanks to you guys, and to all of you here.
P.S. How can I add ASC or DESC for ORDER BY pd.language_id:
$sql .= ' ORDER BY pd.language_id = ' . (int)$this->config->get('config_language_id');
$sql .= ' , LOWER(pd.name) ASC, LOWER(p.model) ASC';
$data = array();
foreach ($res->rows as $values) {
$data[$values['product_id']] = array(
'name' => ...,
'href' => ...
);
}
Guarantees unique product ids only.
The easiest way should be to add another array to track already written ids and check with http://php.net/manual/en/function.in-array.php:
$basehref = 'product/product&keyword=' . $this->request->get['keyword'] . '&product_id=';
$writtenIds = array();
foreach( $data as $key => $values ) {
if(in_array($values['product_id'], $writtenIds))
{
unset($data[$key]);
continue;
}
$data[$key] = array(
'name' => htmlspecialchars_decode($values['name'] . ' (' . $values['model'] . ')', ENT_QUOTES),
'href' => $this->url->link($basehref . $values['product_id'])
);
$writtenIds[] = $values['product_id'];
}
This answer is similar to Marc's except it will preserve the other names in an additional element on the data array for the product_id and it will make sure to remove the sub-arrays that have the same product_id as the first encountered one, which I believe is an important part of what you wanted to do.
$product_ids_added = array();
foreach( $data as $key => $values ) {
$original_key = array_search($values['product_id'], $product_ids_added);
if($original_key===false) {
$data[$key] = array(
'name' => htmlspecialchars_decode($values['name'] . ' (' . $values['model'] . ')', ENT_QUOTES),
'href' => $this->url->link($basehref . $values['product_id'])
);
$product_ids_added[] = $values['product_id'];
}
else {
unset($data[$key]);
if(!isset($data[$original_key]['additional_names'])) $data[$original_key]['additional_names'] = array();
$data[$original_key]['additional_names'][] = htmlspecialchars_decode($values['name'] . ' (' . $values['model'] . ')', ENT_QUOTES);
}
}

All symbols after "&" stripped

My query:
mysql::getInstance()->update('requests', array('response' => mysql_real_escape_string($_POST['status'])), array('secret' => $_POST['secret'])); ?>
If i wand to add string with "&" symbol, all symbols after "&" stripped.
Example:
string: !"№;%:?()_+!##$%^&()_+
in database i see only: !"№;%:?*()_+!##$%^
How to fix this?
update function, if anyone need:
function update($table, $updateList, $whereConditions)
{
$updateQuery = '';
foreach ($updateList as $key => $newValue) {
if (!is_numeric($newValue)) {
$newValue = "'" . $newValue . "'";
}
if (strlen($updateQuery) == 0) {
$updateQuery .= '`' . $key . '` = ' . $newValue;
} else {
$updateQuery .= ', `' . $key . '` = ' . $newValue;
}
}
return $this->query('UPDATE ' . $table . ' SET ' . $updateQuery . $this->buildWhereClause($whereConditions));
}
UPD:
echo mysql::getInstance()->getLastSQL() says:
UPDATE requests SET `response` = '!\"№;%:?*()_ !##$%^' WHERE `secret` = '52a4ab5f7f3e8491e60b71db7d775ee2'
so, problem with function update in mysql class?
Slaks, i need to use str_replace('&', '%28', $query); ?
You're probably passing a raw & character in the querystring, which causes everything after the & to be parsed as second parameter by PHP. (Before it gets into your variable)
You need to escape the & as %26.
EDIT: You need to escape it before you send it to the server. (When you make the HTTP request)

Categories