I just wrote this bit of code which echo's out what it's supposed to but after the echo statement it give me the error-
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
why's this happening? how do i fix it?
<?php
$myclasses = explode(',', $_SESSION['classlist']);
$theirclasses = explode(',', $user_info['classlist']);
$common_classes = array_intersect($myclasses, $theirclasses);
if (count($common_classes) > 0) {
foreach ($common_classes as $class) {
$classes = mysql_query("SELECT * FROM classes WHERE class_id = ".$class) or die(mysql_error());
while($currentRow = mysql_fetch_array($classes)){
echo $currentRow['class_name'];
}
}
}
else {
}
?>
Try wrapping your query with quote:
$classes = mysql_query("SELECT * FROM classes WHERE class_id = '".$class."'") or die(mysql_error());
or change your query altogether by using PDO. Because, mysql_* function are deprecated.
I am going to assume that something is wrong in the $class variable when passed to the query. What I usually do in such scenarios is assign the SQL query to a string variable and dump it to test the entire query at once. Helps me find out SQL syntax errors or if there's any undesired characters.
<?php
$myclasses = explode(',', $_SESSION['classlist']);
$theirclasses = explode(',', $user_info['classlist']);
$common_classes = array_intersect($myclasses, $theirclasses);
if (count($common_classes) > 0) {
foreach ($common_classes as $class) {
$sql = "SELECT * FROM classes WHERE class_id = '{$class}'" ; // use {} inside double quotes
var_dump($sql); // check out the what the query becomes
$classes = mysql_query($sql) or die(mysql_error());
while($currentRow = mysql_fetch_array($classes)){
echo $currentRow['class_name'];
}
}
}
else {
}
If $class is empty you'd get that error which would leave your query as SELECT * FROM classes WHERE class_id = which is not valid. Try quote it. If you quote it, at least you'll get SELECT * FROM classes WHERE class_id = ''
"SELECT * FROM classes WHERE class_id = '".$class."'";
Related
i have 181 fields in my database named S1, S2....S181. I want to update these fields using values from inputs WITH name="S1", .....NAME="S181".
MY CODE IS
$S1=$_POST['S1'];
...
...
$S181=$_POST['S181'];
$sql=mysqli_query($conn,"update 'cap' set S1='$S1'......S181='$S181'")
I am trying something like
for ($i = 1; $i<=181; $i++ ) {
$(S$i)=$_POST['S$i'];
$sql = mysqli_query($conn, "UPDATE `cap4a` SET
S$i='$(S$i)'
WHERE IDID=".$id) or die (mysqli_error($conn));
}
Is there something wrong in the way I use S$i, because I am getting errors:
"Parse error: syntax error, unexpected '(', expecting variable (T_VARIABLE) or '$' in C:\xampp1\htdocs\update_cap4a.php on line 5" ?
I don't think it's a good idea to run 181 queries to alter the same row as you do. Instead, run one query that makes all required changes to the row. The code below will work for you:
$id = (int)$_POST['id'];//remove (int) if id IDID is a string
$snippets = [];//holds little snippets eg: S1='value1'
for($i=1;$i<=181;$i++){
$varname = "S$i"; //S1...S181
if(!isset($_POST[$varname])) continue;
$snippets[] = " $varname='$_POST[$varname]' ";
}
$sql = '"UPDATE cap SET '.implode(",",$snippets)." WHERE IDID=$id";
$result = mysqli_query($conn,$sql) or die (mysqli_error($conn));
I don't cover it in this snippet but you need to add at least two things before using this in production:
Proper error handling, for when your query fails
Prepared statements or escaped values to protect against SQL injection
Is there something wrong in the way I use S$i
To dynamically create a variable named S10 and set it to 'value' when $i=10, do:
$varname = "S$i";
$$varname = 'value'; // $$varname can also be referred to as $S10
See Variable Variables in the docs.
I would gave done it this way:
for ($i = 1; $i<=181; $i++) {
$key = 'S'.$i;
$value = $_POST[$key];
$update[] = "`{$key}` = '".$value."'";
$sql = mysqli_query($conn, "UPDATE `cap4a` SET ".join(",",$update)."
WHERE IDID=".$id) or die (mysqli_error($conn));
}
I'm trying to fetch a result from a mysql table using two form variables namely $sessionID and $semesterID. I used the following code and it seems to have an error in the sql syntax
<?php
...
mysql_select_db($database_connChePortal, $connChePortal);
$query_rsRegcourses =sprintf("SELECT * FROM VW_reg vwr WHERE vwr.sessionID=%s AND vwr.semesterID=%s",$sessionID,$semesterID);
$rsRegcourses = mysql_query($query_rsRegcourses, $connChePortal) or die(mysql_error());
$row_rsRegcourses = mysql_fetch_assoc($rsRegcourses);
$totalRows_rsRegcourses = mysql_num_rows($rsRegcourses);
print_r($query_rsRegcourses); die;
...
?>
I tried running the query and I have the following error report
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 'AND vwr.semesterID=' at line 1
thanks
I think you should surround your variable with single quotes '' please change as follow
"SELECT * FROM VW_reg vwr WHERE vwr.sessionID='%s' AND vwr.semesterID='%s'"
Put the %s in single quotes like this
"SELECT * FROM VW_reg vwr WHERE vwr.sessionID='%s' AND vwr.semesterID='%s'",$sessionID,$semesterID);
To insert a variable into query, you have to properly format it.
Two other answers contains improper formatting - so, you shouldn't follow them.
To make formatting more handy, you have to encapsulate sprintf() into function like this:
function paraQuery()
{
$args = func_get_args();
$query = array_shift($args);
$query = str_replace("%s","'%s'",$query);
foreach ($args as $key => $val)
{
$args[$key] = mysql_real_escape_string($val);
}
$query = vsprintf($query, $args);
$result = mysql_query($query);
if (!$result)
{
throw new Exception(mysql_error()." [$query]");
}
return $result;
}
which would apply proper formatting and also will handle errors
Also note that your way of counting records is extremely inefficient and may cause server to hang. You have to query the only data you need. So, if you need only count - request the count only
so, the code would be
mysql_select_db($database_connChePortal, $connChePortal);
$sql = "SELECT count(*) FROM VW_reg vwr WHERE vwr.sessionID=%s AND vwr.semesterID=%s";
$res = paraQuery($sql,$sessionID,$semesterID);
$row = mysql_fetch_row($res);
print_r($row[0]); die;
it will make your query properly formatted and thus invulnerable to SQL injection
also, it seems that $semesterID is not set which may cause some problem too
I have a form which needs to be updated I get a sql error. Cant see whats going on with my sql statement in my class file. Need assistance in finding where the issue is.
public function update(){
global $database;
$sql = "UPDATE ".self::$table_name." SET when = '{$database->mysql_prep($this->when)}', where = '{$database->mysql_prep($this->where)}', howmuch = '{$database->mysql_prep($this->howmuch)}', contact = '{$database->mysql_prep($this->contact)}', daytimephone = '{$database->mysql_prep($this->daytimephone)}', emailqueries = '{$database->mysql_prep($this->emailqueries)}', websiteurl = '{$database->mysql_prep($this->websiteurl)}', description = '{$database->mysql_prep($this->description)}' WHERE id='{$database->mysql_prep($this->id)}'";
$database->query($sql);
return ($database->affected_rows() == 1) ? true:false;
}
WHEN and WHERE are reserved keywords in MySQL. Enclose them in backticks if you need to use those as field names:
`where`
`when`
I am trying to access some information from mysql, but am getting the warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource for the second line of code below, any help would be much appreciated.
$musicfiles=getmusicfiles($records['m_id']);
$mus=mysql_fetch_assoc($musicfiles);
for($j=0;$j<2;$j++)
{
if(file_exists($mus['musicpath']))
{
echo ''.$mus['musicname'].'';
}
else
{
echo 'Hello world';
}
}
function getmusicfiles($m_id)
{
$music="select * from music WHERE itemid=".$s_id;
$result=getQuery($music,$l);
return $result;
}
Generally, the mysql_* functions are used as follows:
$id = 1234;
$query = 'SELECT name, genre FROM sometable WHERE id=' . $id;
// $query is a string with the MySQL query
$resource = mysql_query($query);
// $resource is a *MySQL result resource* - a mere link to the result set
while ($row = mysql_fetch_assoc($resource)) {
// $row is an associative array from the result set
print_r($row);
// do something with $row
}
If you pass something to mysql_fetch_assoc that is not a MySQL result resource (whether it's a string, an object, or a boolean), the function will complain that it doesn't know what to do with the parameter; which is exactly what you are seeing.
A common gotcha: you get this warning if you pass something (other than a valid query string) to mysql_query:
$id = null;
$query = 'SELECT name, genre FROM sometable WHERE id=' . $id;
$res = mysql_query($query);
// $res === FALSE because the query was invalid
// ( "SELECT name, genre FROM sometable WHERE id=" is not a valid query )
mysql_fetch_assoc($res);
// Warning: don't know what to do with FALSE, as it's not a MySQL result resource
Without seeing the code of getmusicfiles there's not a lot we can really help you with. You should be returning a valid mysql resource in that function.
As others have noted, you need to return a valid mysql resource into the mysql_fetch_assoc function to retrieve the next row. For example:
$sql = "select * from table";
$resultSet = mysql_query($sql) or die("Couldn't query the database.");
echo "Num Rows: " . mysql_num_rows($resultSet);
while ($resultRowArr = mysql_fetch_assoc($resultSet)) {
...
}
I think you need to specify what the function getQuery()
$result=getQuery($music,$l);
does
It depends on what exactly getmusicfiles() does. It must return a result of mysql_query() function call, then it will be a "valid MySQL result".
And you most probably wanted to put the line $mus=mysql_fetch_assoc($musicfiles) inside of the for cycle to fetch several rows one after another.
function getmusicfiles($m_id) {
$music="select * from music WHERE itemid=".$s_id;
$m_id != $s_id ?
I have this code
http://www.nomorepasting.com/getpaste.php?pasteid=22580
which is part of a small ajax application. I would like to know a better, more efficient way to assign $query, instead of copying the sql each time with a different query or a bunch of if clauses. Basically the query will be dependant on the link clicked, but I am not sure how to show that in the logic. I am also unsure why my SQL query in $result fails.
UPDATE: I integrated Eran's function into the refactored code. NOTE: I corrected it by passing the $table variable into it and renamed it since it doesn't search the query text only but mainly returns the needed rows!
MAIN MISTAKES:
mistake 1: you overwrite query with query2 in all cases which breaks the code.
mistake 2: LIKE'%$query%' there is a space missing between LIKE and ' => LIKE '%... this most probably breaks your code too
OTHER ISSUES
security problem: sql injection danger, use mysql_real_escape_string
\n not platform independent: use PHP_EOL
alternative way of writing short if blocks
use curly brackets for normal if structures and all such structures for the matter
here is your code with some changes, look at the comments:
<?php
session_start(); //ommit, no session var used
//use braces, always!
//you may write such statements with the short form like
if (isset($_GET['cmd'])) : $cmd = $_GET['cmd']; else : die (_MSG_NO_PARAM); endif;
$query = '';
//escpae your input - very important for security! sql injection!
if ( isset ($_GET["query"]))
{
$query = mysql_real_escape_string($_GET["query"]);
}
//no need for the other part you had here
$con = mysql_connect("localhost", "root", "geheim");
if (!$con) : die ('Connection failed. Error: '.mysql_error()); endif;
mysql_select_db("ebay", $con);
if ($cmd == "GetRecordSet")
{
$table = 'Auctions';
$rows = getRowsByArticleSearch($searchString, $table);
//use PHP_EOL instead of \n in order to make your script more portable
echo "<h1>Table: {$table}</h1>".PHP_EOL;
echo "<table border='1' width='100%'><tr>".PHP_EOL;
echo "<td width='33%'>Seller ID</td>".PHP_EOL;
echo "<td width='33%'>Start Date</td>".PHP_EOL;
echo "<td width='33%'>Description</td>".PHP_EOL;
echo "</tr>\n";
// printing table rows
foreach ($rows as $row)
{
$pk = $row['ARTICLE_NO'];
echo '<tr>'.PHP_EOL;
echo '<td>'.$row['USERNAME'].'</td>'.PHP_EOL;
echo '<td>'.$row['ACCESSSTARTS'].'</td>'.PHP_EOL;
echo '<td>'.$row['ARTICLE_NAME'].'</td>'.PHP_EOL;
echo '</tr>'.PHP_EOL;
}
}
mysql_free_result($result);
//mysql_close($con); no need to close connection, you better don't
function getRowsByArticleSearch($searchString, $table)
{
$searchString = mysql_real_escape_string($searchString);
$result = mysql_query("SELECT ARTICLE_NO, USERNAME, ACCESSSTARTS, ARTICLE_NAME FROM {$table} WHERE upper ARTICLE_NAME LIKE '%" . $searchString . "%'");
if($result === false) {
return mysql_error();
}
$rows = array();
while($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
}
// ?> ommit closing php tag
"SELECT ARTICLE_NO, USERNAME, ACCESSSTARTS, ARTICLE_NAME
FROM {$table} WHERE upper ARTICLE_NAME LIKE'%$query%'"
You need to put brackets around the parameters of your upper function. change your query to this, and it should work:
"SELECT ARTICLE_NO, USERNAME, ACCESSSTARTS, ARTICLE_NAME
FROM {$table} WHERE upper(ARTICLE_NAME) LIKE'%$query%'"
for a feature use:
$result = mysql_query($sql_query) or die(mysql_error());
To see what kind of mysql error you get.
you should do like nickf said.
and you are definitely prone to SQL-Injection:
wikibooks: http://en.wikibooks.org/wiki/Programming:PHP:SQL_Injection
long article: http://www.securiteam.com/securityreviews/5DP0N1P76E.html
You can abstract your query in a function that accepts the search text as a parameter. Something like:
function searchQuery($text) {
$text = mysql_real_escape_string($text);
$result = mysql_query("SELECT ARTICLE_NO, USERNAME, ACCESSSTARTS, ARTICLE_NAME FROM {$table} WHERE upper ARTICLE_NAME LIKE '%" . $text . "%'");
if($result === false) {
return mysql_error();
}
$rows = array();
while($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
}
Note that you should escape user input to prevent SQL injection attacks (here I used mysql_real_escape_string() to do that). This function also returns the error code if the query fails, so you should check the result to see if it's an array or not:
$result = searchQuery($_GET['query']);
if(!is_array($result) ) {
echo 'An error has occurred:' . $result;
} else {
//iterate over rows
}
Wrap your logical structures (IF/ELSE) with curly brackets {. It's better for readability and helps avoid unnecessary mistakes.
You haven't enclosed the statements in your IF/THEN/ELSE constructions in accolades so only the first statement in every block is conditionally executed, the rest allways is.
In most cases you'd be assigning $query2 to $query while $query2 probably hasn't been defined.
As another tip: sanitize your input, don't go pasting user input into your SQL like that, it's dangerous.
You may need a space between LIKE and '%$query%'. Also, you should look into the mysql_error() function - let MySQL tell you exactly what the error is.