How to update sql like this? - php

Hey,i've got a problem, i want to execute this sql update, but it doesn't work. Could anyone help me? Thanks!
The code:
$temp = $_GET['ul'];
foreach ($temp as $key=> $value)
{
$str=array();
$arr=explode(',',$value);
$str =array($key=>$arr);
for($i=0;$i<count($str[$key]);$i++)
{
$tripID='2';
$sql = "UPDATE places_trips
SET orderNo='$i', ColumnNo='$key'
WHERE place_id=" . $str[$key][$i] . "
AND trip_id=" . $tripID;
mysql_query($sql);
}
}
}
I want to set the $tripID = 2, but actually, $tripID=2222. So how to make the $tripID=2 all the time?

Your query doesn't change trip_id. It tries to change orderNo and ColumnNo for rows where trip_id is 2. If I understand you correctly, you should put it in the first part of your query:
"UPDATE places_trips SET orderNo = '$i', ColumnNo = '$key', trip_id = $tripID WHERE place_id = ".$str[$key][$i];
That being said, read about SQL injections. You need it because your current code is terribly dangerous.

I hope this is what you're after:
UPDATE places_trips SET
orderNo = $i,
ColumnNo = $key
WHERE place_id = $str[$key][$i]
AND trip_id RLIKE '^2+$';
Should update all rows where trip_id contains only 2s.
Also search on StackOverflow for SQL Injections, your code is vulnerable to them.

Related

PHP PDO count and sum value from MySQL table

Well, I'm pretty sure this is just a novice question, so please forgive me for that, but I feel like I'm losing my mind.
I have a simple MySQL rating table and I need to count rows and to sum rates values (int) with PHP PDO
$sql = "SELECT rate FROM rating_table";
$query = $db->query($sql);
$rate_times = count($query->fetchAll()); // it works!
echo '<p>'.$rate_times.'</p>';
$sum_rates = array_sum($query->fetchAll()); // it doesn't work!
echo '<p>'.$sum_rates.'</p>';
Thank you in advance for any suggestion
If I understand you right, all you have to do is to modify your sql request, this will return a single row
sql = "SELECT sum(rate) as rate_sum, count(*) as record_count FROM rating_table";
$query = $db->query($sql);
$row = $query->fetch(PDO::FETCH_ASSOC);
if ($row) {
$sum = $row['rate_sum'];
$count = $row['record_count'];
}

How do I create a parameterized database update statement in Yii for an IN() clause?

I tried
$sql = "update ad_group_keyword set status = :status where google_id not in (:google_id)";
Yii::$app->db->createCommand($sql)
->bindValue(':status', Constants::DELETED)
->bindValue(':google_id', join(',',$googleIds), \PDO::PARAM_INT)
->execute();
but it turned the array of ids into one giant string, despite the PDO::PARAM_INT. I also tried
->bindValue(':google_id', $googleIds)
but it gave an 'Array to string conversion' in vendor/yiisoft/yii2/db/Command.php:172. I ended up using
$sql = "update ad_group_keyword set status = :status where google_id not in (" . join(',',$googleIds) . ")";
I suggest use QueryBuilder for this function:
$command = Yii::$app->db->createCommand();
$result = $command->update( // create a update sql
'ad_group_keyword', // table
['status'=>1], // update set
['NOT IN', 'google_id', [1,2,3]] // where
)->execute();
You can read the \yii\db\Command::update() DOC, and how to set condition
You shouldn't have a join in there at that place. That is where it is being turned into a string. You want to iterate through your list of ids and bindValue each one to the variable in turn.
You'll need to bind each of the array values individually. Something like this:
$sql = "UPDATE ad_group_keyword
SET status = :status
WHERE google_id NOT IN(%s)";
$bindValues = array();
$i = 0;
foreach ($googleIds as $value)
{
$bindValues[':googleId'.$i++] = $value;
}
$sql = sprintf($sql, join(', ', array_keys($bindValues)));
$sqlCommand = Yii::$app->db->createCommand($sql);
$sqlCommand->bindValue(':status', Constants::DELETED);
foreach ($bindValues as $key => $value)
{
$sqlCommand->bindValue($key, $value, \PDO::PARAM_INT);
}
$sqlCommand->execute();
However, I'm only basing this example on your code and I'd look into Yii's manual to see if there already isn't a method that does all of this work for you ... it shouldn't be that hard to safely execute an SQL query using IN().

Pointless SQL vs PHP if

I need to manipulate entries in a mySQL table using code like this
foreach($items as $item)
{
$sql = "UPDATE `siteims` SET refs = refs + 1 WHERE imid = '{$item->img}';";
$sql .= "UPDATE `lists` SET refs = refs + 1 WHERE lid = '{$item->lili}'";
$dbh->exec($sql);
}
There may be as many as 50 items in $items. A variation on this code would be
foreach($items as $item)
{
if ('z' != $img->img)
$sql = "UPDATE `siteims` SET refs = refs + 1 WHERE imid = '{$item->img}';";
if ('z' != $item->lili)
$sql .= "UPDATE `lists` SET refs = refs + 1 WHERE lid = '{$item->lili}'";
$dbh->exec($sql);
}
In both cases I am executing a sequence of SQL statements for EACH item in $items. My questions
Would it not be a whole lot more efficient to build $sql for items and then execute it?
But then if all of the, potentially, 50 items in $items produces meaningful SQL would that not mean a very slowly executing batch of SQL statements?
Finally, is it better to perform PHP side if tests as in the second version of my code or just build the SQL and let mySQL deal with the fact that the WHERE test returns an empty row?
I'd much appreciate any help with this.
You could use an in clause, instead, e.g.
$sql = "UPDATE .... WHERE imid IN (" . implode($array_that_has_the_ids) . ")"
and reduce yourself down to just one single SQL query. However, this can fail if you're trying to use a HUGE aray - the generated query could exceed the max_allowed_packet setting and get killed.
As for your strlen... what's the point of comparing strlen results against 'z'? strlen returns an integer, you might as well be doing if (apple == orange) instead.
At first place I advice you to use IN clause and just 2 separated queries...
You may have to escape those 2 elements $item->img and $item->lili ..
$ids = array("siteims"=>array(), "lists"=>array());
foreach($items as $item)
{
$ids['siteims'][] = "'" . $item->img . "'";
$ids['lists'][] = "'" . $item->lili . "'" ;
}
if(!empty($ids['siteims'])){
$sql = "UPDATE `siteims` SET refs = refs + 1 WHERE imid IN (".implode(',', $ids["siteims"]).")";
$dbh->exec($sql);
}
if(!empty($ids['lists'])){
$sql = "UPDATE `lists` SET refs = refs + 1 WHERE lid IN (".implode(',', $ids["lists"]).")";
$dbh->exec($sql);
}

How to fetch single row from Oracle in PHP?

I want to know how to fetch single row from Oracle in PHP?
Chedck my script-:
I want to fetch single row from ITEM_INFO table & compare that values with variables $sku & $code...Logic I applied which works in Mysql but not working in Oracle...
Each time $sku & $code contains diff. values so I just need to compare them with ITEM_INFO table & if it's matches then update the flag for the same...
$query_fetch = "SELECT ITEM_NAME,SITE_CODE FROM app.ITEM_INFO WHERE ITEM_FLAG = 'N'";
$stmt = oci_parse($conn,$query_fetch);
oci_execute($stmt);
while(($row = oci_fetch_array($stmt, OCI_BOTH)))
{
$ITEM_NAME = ($row["ITEM_NAME"]);
$SITE_CODE = ($row["SITE_CODE"]);
if(($ITEM_NAME === $sku) && ($SITE_CODE === $code))
{
$query_ora_update = "UPDATE app.ITEM_INFO SET ITEM_FLAG= 'Y', LAST_UPDATE_DATE = sysdate WHERE ITEM_NAME = '$sku' AND SITE_CODE = '$code' AND ITEM_FLAG = 'N' ";
$parse_result = oci_parse($conn,$query_ora_update);
$result = oci_execute($parse_result);
oci_commit($conn);
oci_close($conn);
}
}
plz guide me...
Basically, you just have to remove the while loop.
Here's a rewrite of your code applying that change (+ you use too many parenthesis, decreasing your code readability + you should use SQL binding to avoid injection):
$query_ora_update = "UPDATE app.ITEM_INFO SET ITEM_FLAG= 'Y', LAST_UPDATE_DATE = sysdate WHERE ITEM_FLAG = 'N'";
$parse_result = oci_parse($conn, $query_ora_update);
$result = oci_execute($parse_result);
oci_commit($conn);
oci_close($conn);
To fetch a single row in Oracle, add in your where clause the following condition:
ROWNUM = 1
Unfortunately could not understand the rest of your code, did not understand why the "ifs" if you already have the same condition in the where clause of your update.
The Oracle equivalent to mysql_fetch_assoc is oci_fetch_assoc :)
$parsed = ociparse($conn, $sql);
while ($row = oci_fetch_assoc($parsed))
{
// your logic here
}

I want to do a sql update loop statement, by using the do--while in php

I want to loop the update statement, but it only loops once.
Here is the code I am using:
do {
mysql_select_db($database_ll, $ll);
$query_query= "update table set ex='$71[1]' where field='val'";
$query = mysql_query($query_query, $ll) or die(mysql_error());
$row_domain_all = mysql_fetch_assoc($query);
} while ($row_query = mysql_fetch_assoc($query));
Thanks
Jean
Well, the reason it's only looping once would be that UPDATE queries do not return any rows that you could extract with mysql_fetch_assoc. So mysql_fetch_assoc returns false, which renders the expression ($row_query = mysql_fetch_assoc($query)) false, which is why the loop aborts.
Apart from that though, that code is, sorry to say, pretty atrocious. It might help telling us what it is you want to do, there must be a better way.
The problem is you reattribute a value to $query within your loop. Try
do {
mysql_select_db($database_ll, $ll);
$query_query= "update table set ex='$71[1]' where field='val'";
$query2 = mysql_query($query_query, $ll) or die(mysql_error());
$row_domain_all = mysql_fetch_assoc($query2);
} while ($row_query = mysql_fetch_assoc($query));
may be it has some problem in your mysql query.
$query_query= "update table set ex='$71[1]' where field='val'";
Your query is wrong.
update query is "update "table name" set ex='$71[1]' where field='val'";
You missed the table name.
or if you are using 'table' as your table name. then change it.
People,
I needed to replace this
$query = mysql_query($query_query, $ll) or die(mysql_error());
$row_domain_all = mysql_fetch_assoc($query);
With
$Result1 = mysql_query($query_query, $ll) or die(mysql_error());

Categories