pq_query error on update - php

I'm new to postresql and i am ashamed to recognize that i am not sure how tot execute correctly an update .
Every time I am trying to pg_query($update); it gives me this : Query failed: ERROR: cannot execute UPDATE in a read-only transaction .
Before this update I have executed a select query .
The select statement retrieves 50000 rows from the database. To be even more specific I am trying to execute a when /case update on 1000 rows. The query is well-formed I have tested it .
$sqlstr = "update abcd set country = CASE" ;
$temp = "";
while($myrow = pg_fetch_assoc($result)) {
if ($cnt < 1000) {
$country = exec('geoiplookup '.$myrow['ip']);
$temp .= " WHEN id = ".$myrow['id']." then '".$country."'";
$cnt++;
}
else {
$sqlstr = $sqlstr.$temp." END ; ";
pg_query($sqlstr);
$temp = "";
}
}

$sqlstr = "update abcd set country = CASE" ;
$temp = "";
while($myrow = pg_fetch_assoc($result))
{
if ($cnt < 1000)
{
$country = exec('geoiplookup '.$myrow['ip']);
$temp .= " WHEN id = ".$myrow['id']." then '".$country."'";
$cnt++;
}
else
{
$sqlstr = $sqlstr.$temp." END ; ";
pg_query($sqlstr);
$temp = "";
}
}

Related

possible ?: mysql row to an if condition

hi guys im trying to insert a mysql data to a variable that will set an if condition depending on the result. is this possible, am i doing it right? what is the right way to do it ? what i want to achieve is to validate if there's a equal value given by the user inside my mysql rows.
$db = mysql_connect('localhost','test','');
if (!$db)
{
print "<h1>Unable to Connect to MySQL</h1>";
}
$dbname = 'test';
$btest = mysql_select_db($dbname);
if (!$btest)
{
print "<h1>Unable to Select the Database</h1>";
}
$sql_statement = "SELECT * ";
$sql_statement .= "FROM registered_email ";
$result = mysql_query($sql_statement);
$outputDisplay = "";
$myrowcount = 0;
if (!$result) {
$outputDisplay .= "<br /><font color=red>MySQL No: ".mysql_errno();
$outputDisplay .= "<br />MySQL Error: ".mysql_error();
$outputDisplay .= "<br />SQL Statement: ".$sql_statement;
$outputDisplay .= "<br />MySQL Affected Rows: ".mysql_affected_rows()."</font><br />";
}
else{
$numresults = mysql_num_rows($result);
for ($i = 0; $i < $numresults; $i++)
{
$row = mysql_fetch_array($result);
$id = $row['id'];
$sentEmailClients = $row['email'];
$outputDisplay.= "".$sentEmailClients."<br />";
}
}
and here what im trying to achieve, btw is $clientEmail has a default values so dont worry about that.
if($clientEmail === $outputDisplay){
...... some codes..........
}
else{
....... some codes.......
}
you can use mysql row to compare with your user input. you can add condition, while you'r getting row value for the email inside the loop.
$email_exist = 0;//define the default value.
for ($i = 0; $i < $numresults; $i++)
{
$row = mysql_fetch_array($result);
$id = $row['id'];
$sentEmailClients = $row['email'];
$outputDisplay.= "".$sentEmailClients."<br />";
//my code start here
if($sentEmailClients == $clientEmail)
$email_exist = 1;
}
//outside the loop
if($email_exist == 1) {
//..........write some code.......
}else{
//........write some code.......
}
why don't you use a while loop?
make sure to update to mysqli_* because mysql_* is deprecated and is going to get removed on php 7.0
$email_exist = 0;//define the default value.
while ( $row = mysql_fetch_assoc($result) ) // you are using associative array and not the indexed once tho you should go for mysql_fetch_assoc
{
$id = $row['id'];
$sentEmailClients = $row['email'];
$outputDisplay.= "".$sentEmailClients."<br />";
//my code start here
if($sentEmailClients == $clientEmail)
$email_exist += 1; //maybe it exist more than once?
}
//outside the loop
if($email_exist == 1) {
//..........write some code.......
}else{
//........write some code.......
}
or you can do something more simple like this
$query = "select email from tablename where email='$clientemail'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count > 0) {
// email exists
} else {
// doesn't exist
}

PHP: Loop looping through result set

I am having a huge issue looping through results, These two queries work hand in hand to check if a restaurant is open today. My problem is i have restaurants, id 1-5(more in the future). But the loop seems to only get restaurant id 5. I have read many posts on here and it seems like i am doing the right thing. But i cannot seem to loop to get the other restaurant id's.
I am blocked now, newbie who is very open to any suggestions or advise.
$sel = "SELECT Rest_Details.Resturant_ID,Delivery_Pcode.Pcode,Delivery_Pcode.Restaurant_ID
FROM Rest_Details INNER JOIN Delivery_Pcode
ON Delivery_Pcode.Restaurant_ID=Rest_Details.Resturant_ID
WHERE Delivery_Pcode.Pcode LIKE'$searchP'";
$res = $dbc->query($sel);
if (!$res) {
echo "invalid query '" . mysqli_error($dbc) . "\n";
}
$i=1;
while ($row_res = $res->fetch_array()) {
$rest_ = $row_res['Resturant_ID'];
$i++;
}
date_default_timezone_set("Europe/London");
$daynum = jddayofweek(unixtojd());
$query = "SELECT *
FROM Opening_hrs WHERE
Restaurant_ID = $rest_
AND Day_of_week = $daynum";
$run_qu = $dbc->query($query);
if ($run_qu->num_rows > 0) {
while ($row_qu = $run_qu->fetch_assoc()) {
$message = "open" . $row_qu["Open_time"] . "</br>";
}
} else {
$message = $message . "close" . $row_qu["Closing_time"] . "</br>";
}
You could either output whatever you want to within your loop or build-up an output string because the value of $rest_ will always be the last value in the loop and i don't think that's what you want... Again you are doing the same with $message. And I am willing to bet that this is what you want to do:
<?php
date_default_timezone_set("Europe/London");
$sel = "SELECT Rest_Details.Resturant_ID,Delivery_Pcode.Pcode,Delivery_Pcode.Restaurant_ID
FROM Rest_Details INNER JOIN Delivery_Pcode
ON Delivery_Pcode.Restaurant_ID=Rest_Details.Resturant_ID
WHERE Delivery_Pcode.Pcode LIKE'$searchP'";
$res = $dbc->query($sel);
if (!$res) {
echo "invalid query '" . mysqli_error($dbc) . "\n";
}
$i=1;
while ($row_res = $res->fetch_array()) {
$rest_ = $row_res['Resturant_ID'];
$i++; // <== YOU DON'T NEED THIS VARIABLE....
// GET THE DATES WITHIN THE LOOP...
$daynum = jddayofweek(unixtojd());
$query = "SELECT *
FROM Opening_hrs WHERE
Restaurant_ID = $rest_
AND Day_of_week = $daynum";
$run_qu = $dbc->query($query);
if ($run_qu->num_rows > 0) {
while ($row_qu = $run_qu->fetch_assoc()) {
$message = "open" . $row_qu["Open_time"] . "</br>";
}
} else {
$message = $message . "close" . $row_qu["Closing_time"] . "</br>";
}
}
I think this is what you are trying to do.
// $searchP should be checked to prevent SQL injection.
$sel = "SELECT Rest_Details.Resturant_ID, Delivery_Pcode.Pcode,
Delivery_Pcode.Restaurant_ID
FROM Rest_Details INNER JOIN Delivery_Pcode
ON Delivery_Pcode.Restaurant_ID = Rest_Details.Resturant_IDW
WHERE Delivery_Pcode.Pcode LIKE '$searchP'";
$res = $dbc->query($sel);
if (!$res) {
echo "invalid query '" . mysqli_error($dbc) . "\n";
}
// set these once as they don't change
date_default_timezone_set("Europe/London");
$daynum = jddayofweek(unixtojd());
// $i=1; - not required, never used
// loop over the original results
while ($row_res = $res->fetch_array()) {
$rest_ = $row_res['Resturant_ID'];
//$i++; not used
// check for a match
$query = "SELECT * FROM Opening_hrs
WHERE Restaurant_ID = $rest_
AND Day_of_week = $daynum";
$run_qu = $dbc->query($query);
if ($run_qu->num_rows > 0) {
// at least one match
while ($row_qu = $run_qu->fetch_assoc()) {
$message = "open" . $row_qu["Open_time"] . "<br />";
$message .= "close" . $row_qu["Closing_time"] . "<br />";
}
} else {
// no matches
$message = "No results for <i>$daynum</i>.";
}
}
It should be possible to get the details in a single query, but I would need to see your SQL tables for that (and you did not ask for that too :]).
Also, it is <br> or <br />, not </br>.

query works in mysql terminal but not in php

I build my query in PHP dynamically, and when I try to execute it, it fails. When I copy the query it generated and paste it into the mysql terminal and run it, it works fine. The error I get is "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '>' at line 1" for the following query:
UPDATE events SET event = 'orgo lecture', start = '2014-07-24 16:00:00' WHERE userID = 1 AND eventID = 5
The following is the code used to generate the query dynamically:
$query = "UPDATE events SET ";
$query_list = array();
if ($set_event) {
$query_list[] = "event = '{$event}'";
}
if ($set_start) {
$query_list[] = "start = '{$start}'";
}
if ($set_end) {
$query_list[] = "end = '{$end}'";
}
$query_list_size = count($query_list);
for ($i = 0; $i < $query_list_size - 1; $i++) {
$query .= $query_list[$i];
$query .= ", ";
}
$query .= $query_list[$query_list_size - 1];
$query .= " WHERE userID = {$userID} AND eventID = {$eventID}";
echo $query .= "<br />";
$query_result = mysqli_query($connection, $query) or die(mysqli_error($connection));
This issue is this:
echo $query .= "<br />";
Should be
echo $query . "<br />";
Ironically, by checking your query you were breaking it.
As a side note,
$query_list_size = count($query_list);
for ($i = 0; $i < $query_list_size - 1; $i++) {
$query .= $query_list[$i];
$query .= ", ";
}
$query .= $query_list[$query_list_size - 1];
Could be shortened to:
$query .= implode(", ", $query_list);
The echo $query .= "<br />"; instruction is changing the query and making it invalid SQL. Why not use echo $query . "<br />";?

While Loop in SQL query

I'm not sure why this SQL query is not working.
I'm new to SQL/PHP so please forgive.
mysql_query("
SELECT * FROM table WHERE name = " . "'Bob'" .
while($i < $size)
{
$i++;
echo "OR name = '";
echo $array[$i] . "'";
} .
" ORDER BY id DESC "
);
Dreamweaver gives me an error saying it is not correct but does not tell me what is wrong.
Is it possible to put a while loop into an sql command?
you can not use a while in a string
$where = "";
if ($size > 0)
{
$where .= " WHERE ";
}
while($i < $size)
{
$i++;
$where .= "OR name = '".$array[$i]."' ";
}
$query = "SELECT * FROM table WHERE name = '".Bob."'".$where." ORDER BY id DESC";
mysql_query($query);
(this code is not tested)
Woot !
You just can't write this :D
Build your OR condition before writing the query and it will be just fine:
$myCondition = " ";
while($i < $size) {
$i++;
$myCondition .= "OR name = '" . $array[$i] . "'";
}
mysql_query(
"SELECT * FROM table WHERE name = " . "'Bob'" . $myCondition . " ORDER BY id DESC ");
echo is to output the string, and it won't return the string.
Something like $str = "aaa" . echo "bbb"; won't work.
For you case, use IN will be better.
foreach ($array as &$name) {
$name = "'".mysql_real_escape_string($name)."'";
}
mysql_query("SELECT * FROM table WHERE name IN (".implode(',', $array).")");
Or use
"SELECT * FROM table WHERE name IN(".implode( ',', $array).")";

SQL Multiple WHERE Clause Problem

I'm attempting the modify this Modx Snippet so that it will accept multiple values being returned from the db instead of the default one.
tvTags, by default, was only meant to be set to one variable. I modified it a bit so that it's exploded into a list of variables. I'd like to query the database for each of these variables and return the tags associated with each. However, I'm having difficulty as I'm fairly new to SQL and PHP.
I plugged in $region and it works, but I'm not really sure how to add in more WHERE clauses for the $countries variable.
Thanks for your help!
if (!function_exists('getTags')) {
function getTags($cIDs, $tvTags, $days) {
global $modx, $parent;
$docTags = array ();
$baspath= $modx->config["base_path"] . "manager/includes";
include_once $baspath . "/tmplvars.format.inc.php";
include_once $baspath . "/tmplvars.commands.inc.php";
if ($days > 0) {
$pub_date = mktime() - $days*24*60*60;
} else {
$pub_date = 0;
}
list($region, $countries) = explode(",", $tvTags);
$tb1 = $modx->getFullTableName("site_tmplvar_contentvalues");
$tb2 = $modx->getFullTableName("site_tmplvars");
$tb_content = $modx->getFullTableName("site_content");
$query = "SELECT stv.name,stc.tmplvarid,stc.contentid,stv.type,stv.display,stv.display_params,stc.value";
$query .= " FROM ".$tb1." stc LEFT JOIN ".$tb2." stv ON stv.id=stc.tmplvarid ";
$query .= " LEFT JOIN $tb_content tb_content ON stc.contentid=tb_content.id ";
$query .= " WHERE stv.name='".$region."' AND stc.contentid IN (".implode($cIDs,",").") ";
$query .= " AND tb_content.pub_date >= '$pub_date' ";
$query .= " AND tb_content.published = 1 ";
$query .= " ORDER BY stc.contentid ASC;";
$rs = $modx->db->query($query);
$tot = $modx->db->getRecordCount($rs);
$resourceArray = array();
for($i=0;$i<$tot;$i++) {
$row = #$modx->fetchRow($rs);
$docTags[$row['contentid']]['tags'] = getTVDisplayFormat($row['name'], $row['value'], $row['display'], $row['display_params'], $row['type'],$row['contentid']);
}
if ($tot != count($cIDs)) {
$query = "SELECT name,type,display,display_params,default_text";
$query .= " FROM $tb2";
$query .= " WHERE name='".$region."' LIMIT 1";
$rs = $modx->db->query($query);
$row = #$modx->fetchRow($rs);
$defaultOutput = getTVDisplayFormat($row['name'], $row['default_text'], $row['display'], $row['display_params'], $row['type'],$row['contentid']);
foreach ($cIDs as $id) {
if (!isset($docTags[$id]['tags'])) {
$docTags[$id]['tags'] = $defaultOutput;
}
}
}
return $docTags;
}
}
You don't add in more WHERE clauses, you use ANDs and ORs in the already existing where clause. I would say after the line $query .= " WHERE stv.name = '".$region... you put in
foreach ($countries as $country)
{
$query .= "OR stv.name = '{$country}', ";
}
but I don't know how you want the query to work.

Categories