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 />";?
Related
Does anybody know what could be wrong here?
<?php
$q = intval($_GET['q']);
echo $q." "; // $q=2
$d = $_GET['d'];
echo $d." "; //$d=3priority
$m = preg_replace('/[0-9]+/', '', $d);
echo $m." "; //$m = priority
$s = intval($_GET['d']);
echo $s;// $s = 3
$sql = "UPDATE form SET $m = $q WHERE id = $s";
$result = $conn->query($sql);
if ($conn->query($sql) === TRUE) {echo "das";}
else{
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
I get the Error Message :
UPDATE form SET = 0 WHERE id = 0 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 '= 0 WHERE id = 0' at line 1
However if I echo the $m/$q/$s/$d thy show the right values. But somehow they get changed to 0 in the sql statement.
Would be nice if you could help me out :)
Try This
$sql = "UPDATE form SET" . $m . "=" . $q . " WHERE id =" . $s;
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 = "";
}
}
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).")";
i am a beginner. but I'm practicing a lot for few days with php mysql, and I am trying to use for loop to search an exploded string, one by one from mysql server.
Till now I have no results.
I'm giving my codes,
<?php
// Example 1
$var = #$_GET['s'] ;
$limit=500;
echo " ";
echo "$var";
echo " ";
$trimmed_array = explode(" ", $var);
echo "$trimmed_array[0]"; // piece1
echo " ";
$count= count($trimmed_array);
echo $count;
for($j=0;$j<$count;$j++)
{
e cho "$trimmed_array[$j]";;
echo " ";
}
echo " ";
for($i=0; $i<$count ; $i++){
$query = "select * from book where name like \"%$trimmed_array[$i]%\" order by name";
$numresults=mysql_query($query);
$numrows =mysql_num_rows($numresults);
if ($numrows == 0)
{
echo "<h4>Results</h4>";
echo "<p>Sorry, your search: "" . $trimmed_array[i] . "" returned zero results</p>";
}
if (empty($s)) {
$s=0;
}
$query .= " limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
echo "<p>You searched for: "" . $var . ""</p>";
echo "Results<br /><br />";
$count=1;
while ($row= mysql_fetch_array($result)) {
$name = $row["name"];
$publisher=$row["publisher"];
$total=$row["total"];
$issued=$row["issued"];
$available=$row["available"];
$category=$row["category"];
echo "<table border='1'><tr><td>$count)</td><td>$name </td><td>$publisher </td><td>$total </td><td>$issued </td><td>$available </td><td>$category </td></tr></table>" ;
$count++ ;
}
}
?>
In your case, you do for every record in your array ($trimmed_array) a new select. Thats not really good.
It would be better when you create just one select...
For example this:
// you need 1=1 for example when $i<count is false...
$baseQuery = "select * from book where 1=1";
$query = $baseQuery;
for($i=0; $i<$count ; $i++){
$query .= " OR name like ?";
}
// do your ordering:
$query.= " order by name";
But what does this "?" mean?
--> Do you know what sql-injection means? somebody could really easy put some information in this array wich could give any information about your database.. therefore you have to escape every userinput...
i like the mysqli package in php5. watch this example:
$query = "SELECT `id` FROM employees WHERE `name`=?";
// Setup parameter to be bound into query
$name = "Joey";
// Get instance of statement
$stmt = $mysqli->stmt_init();
// Prepare Query
if($stmt->prepare($query)){
// Bind Parameters [s for string]
$stmt->bind_param("s",$name);
// Execute statement
$stmt->execute();
// Bind result variables
$stmt->bind_result($employee_id);
// Fetch Value
$stmt->fetch();
// Echo results
echo "$name has an ID of $employee_id";
// Close Statement
$stmt->close();
}
Damn, your code really extremely crazy. Here you example about how to work with this:
<?php
$var = $_GET['s'];
$exp = explode(" ",$var);
$total = count($exp) - 1;
for($i = 0; $i <= $total; $i++) {
echo "Search for: " . $exp[$i] ."\n";
$sql = mysql_query("SELECT * FROM `book` WHERE `name` LIKE '%" . mysql_real_escape_string($exp[$i]) ."%'") or die(mysql_error());
if (mysql_fetch_num($sql) != 0) {
// Somthing found
}
}
?>
You have an error on line 25,
e cho "$trimmed_array[$j]";;
should be
echo "$trimmed_array[$j]";
Also, it seems that you are using $GET_[] variables, which are passed via the url string, which does not allow spaces. On line 15, you are splitting the array with explode(" ", $var);
I would also urge you, if you have not, look into sanitizing your database queries.
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.