what is the correct syntax for query - php

how can I get this syntax work? I got it to work with one of the result. But I want to
get out query from 3. (result1, result2, result3).
$sql = "SELECT modulid=1 FROM oppgave WHERE resultat resultat2 resultat3 is NULL ORDER BY RAND() LIMIT 1";
any tip how to query 3 ?

Try below:
If you want to check that any one should be null of of resultat, resultat2 and resultat3, then use below query:
SELECT moduleid
FROM oppgave
WHERE modulid=1 and (resultat is null or resultat2 is null or resultat3 is NULL)
ORDER BY RAND() LIMIT 1;
If you want to check that all resultat, resultat2 and resultat3 should be null, then use below query:
SELECT moduleid
FROM oppgave
WHERE modulid=1 and (resultat is null and resultat2 is null and resultat3 is NULL)
ORDER BY RAND() LIMIT 1;

Rewrite your query like this..
SELECT *
FROM oppgave
WHERE modulid=1
AND
coalesce(resultat, resultat2, resultat3) IS NULL
ORDER BY RAND() LIMIT 1;
Proceed like this..
$result = mysql_query($sql, $tilkobling);
echo "<br>";
while ($nextrow= mysql_fetch_array($result)){
echo "Besvarelse: <br>" . $nextrow['besvarelse']; "<br>Modulid: " . $nextrow['modulid'];
}
This (mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, Prepared Statements of MySQLi or PDO_MySQL extension should be used to ward off SQL Injection attacks !

Related

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error

I'm using php and pdo
Here is my code:
try {
$sql="LOCK TABLE appleid WRITE, appleid AS appleid1 READ;";
$stmt = $GLOBALS['$connection']->prepare($sql);
$stmt->execute();
$sql="SELECT MAX(num) FROM appleid;";//to know how many rows it has
$stmt = $GLOBALS['$connection']->prepare($sql);
$stmt->execute();
$result=$stmt->fetch();
$table_top=$result[0];
if (empty($head)) $head = 1;
$check=$table_top - $head;
$check++;//number of available rows that are ready to use
if($check>=$this->apple_id_num)
{
$sql = "SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM
appleid AS appleid1
WHERE num>=$head LIMIT $this->apple_id_num ORDER BY `TimeStamp`
DESC;";
$stmt = $GLOBALS['$connection']->prepare($sql);
$stmt->execute();
$this->pre_head=$head;
$head=1+$head+$this->apple_id_num;
$sql="UNLOCK TABLES;";
$this->num_rows = $stmt->rowCount();
echo $stmt->rowCount();
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
I get this error :
SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM appleid AS
appleid1 WHERE num>=1 LIMIT 1 ORDER BY TimeStamp DESC;
SQLSTATE[42000]: Syntax error
or access violation: 1064 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 'ORDER BY TimeStamp DESC' at line 2
I got confused and I don't know what is wrong with this query and how to fix it.
SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM
appleid AS appleid1
WHERE num>=$head ORDER BY `TimeStamp`
DESC LIMIT $this->apple_id_num ;
put your limit after orderby
Use orderby clause before limit clause.
$sql = "SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM
appleid AS appleid1
WHERE num>=$head ORDER BY `TimeStamp` DESC LIMIT $this->apple_id_num;";
Change
"SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM
appleid AS appleid1
WHERE num>=$head LIMIT $this->apple_id_num ORDER BY `TimeStamp`
DESC;";
to
"SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM
appleid AS appleid1
WHERE num>=$head LIMIT {$this->apple_id_num} ORDER BY `TimeStamp`
DESC;";
since the double quotes would not know whether to parse the ->apple_id_num as string or part of a variable.
I have not tested, but timeStamp sound like a reserved word of mysql,
maybe you can try a correct quote of this field, or best pratice change the name of the field.

Unable to run named placeholder for order by ASC in php pdo

I am new to PHP PDO and trying to use named placeholder at the place of ORDER BY ASC. Sometime in simple query page this run very successfully but unable to run in the following query:
PHP CODE IS:
$price_sort = "ASC";
$keyword = "samsung glaxy";
$limit = 0;
$query = $db->prepare("SELECT *, MATCH(title) against (:keyword) as 'relevence'
FROM view_store_items_grid
WHERE MATCH(title) against(:keyword)
ORDER BY relevence DESC, price :order
LIMIT :limit,25");
$query->bindValue(":keyword",$keyword);
$query->bindValue(":order",$price_sort);
$query->bindValue(":limit", $limit, PDO::PARAM_INT);
$query->execute();
When I remove placeholder :order with ASC this run and gives result but when I use this placeholder, I get empty result.
For Fetching data or to show fetched result I am using
while ($row = $query->fetch(PDO::FETCH_ASSOC)) :
extract($row);
echo "$name";
endwhile;
What I am doing wrong and How I can use many named placeholder in query at different places?
You should not bind ASC/DESC in prepared statement. Parameters are automatically quoted, and ASC/DESC shouldn't be quoted. this is the same reason that table and column names can't be parameters.
Instead you can do like that
$sql_query = "SELECT *, MATCH(title) against (:keyword) as 'relevence'
FROM view_store_items_grid
WHERE MATCH(title) against(:keyword)
ORDER BY relevence DESC, price "
if($price_order == 'ASC'){
$sql_query .= " ASC "
}else{
$sql_query .= " DESC "
}
$sql_query .= " LIMIT :limit,25 "
$query = $db->prepare($sql_query);
Refer How bindValue in LIMIT
Refer pdo binding asc/desc order dynamically
Also do not try to use the same named parameter twice in a single SQL statement, for example
<?php
$sql = 'SELECT * FROM some_table WHERE some_value > :value OR some_value < :value';
$stmt = $dbh->prepare($sql);
$stmt->execute( array( ':value' => 3 ) );
?>
...this will return no rows and no error -- you must use each parameter once and only once. Apparently this is expected behavior (according to this bug report: http://bugs.php.net/bug.php?id=33886) because of portability issues.
This one solved this question by replacing the price_sort variable value with price ASC and removing the price before the placehoder :order
as:
$price_sort = "price ASC";
and the query is as:
$query = $db->prepare("SELECT *, MATCH(title) against (:keyword) as 'relevence'
FROM view_store_items_grid
WHERE MATCH(title) against(:keyword)
ORDER BY relevence DESC, :order
LIMIT :limit,25");
this solved my question with the help of answer of #tamil
Thank you

MYSQL-counting distinct cell values

I tried to count using following-
include 'db_login';
$sql = "(SELECT * , COUNT(*) FROM `table1`
WHERE `ADVERTISERCATEGORY` LIKE '%something%'
GROUP BY `MANUFACTURER` ORDER BY COUNT DESC )";
$row = mysql_fetch_array($sql);
$total = $row[0];
echo "Total rows: " . $total;
but i got following error message-
Warning: mysql_fetch_array() expects parameter 1 to be resource,
string given in /home/content/43/10130843/html/fashion_test.php on line 169
i am learning php/mysql therefore i need help.
thanks
You haven't called mysql_query(), so you can't fetch the array yet...
$sql = "SELECT * , COUNT(*) FROM `table1`
WHERE `ADVERTISERCATEGORY` LIKE '%something%'
GROUP BY `MANUFACTURER` ORDER BY COUNT(*) DESC ";
$query = mysql_query($sql) or die(mysql_error()); // exit on error
$row = mysql_fetch_array($query);
Note: mysql_query() and the rest of the mysql_* library have been deprecated for some time, you should make the move to paramterized queries with mysqli_* or PDO while you're in the development phase.

php MySQL query not returning anything

I'm not sure exactly how to explain what the query does, however the problem isn't entirely with how it's set up, because it does work, in another instance, when I use it as an array, however it's not working when I use it with mysql_fetch_assoc(), so here is what my original query is(not the one im having trouble with):
SELECT * FROM
(SELECT * FROM comments
WHERE postID='$id' AND state='0'
ORDER BY id DESC LIMIT 3
) t ORDER BY id ASC
what this does is selects the last 3 comments on a post, then orders them in another way (so they show up in the correct order, old to new) Now this is the query for echoing out the array of comments directly.
But now what I want to do, is to just get the first id out of the 3 comments.
here's what I have tried to do (and by the way, this query DOES work, when i replace my previous query to echo out the results in an array, but i need to get just the id for use, i don't want an array):
$previousIDq = mysql_fetch_assoc(mysql_query("
SELECT * FROM
(SELECT * FROM comments
WHERE postID='$id' AND state='0'
ORDER BY id DESC LIMIT 3
) t ORDER BY id ASC LIMIT 1"));
$previousID = $previousIDq['id']; //this doesn't return the id as I want it to.
Your problem may be that there are no matching rows.
Also, I think you could also improve your query to this:
SELECT * FROM comments WHERE postID='$id' AND state='0' ORDER BY id DESC LIMIT 2,1
But as others say, use PDO or MySQLi, and with prepared statements. And don't SELECT * ever.
try a var_dump($previousID) to see what you get
It is probably giving you back an object, and you need to get your id from that object
You script is too condensened for error handling, let alone debugging
$mysql = mysql_connect(...
$query = "
SELECT * FROM
(SELECT * FROM comments
WHERE postID='$id' AND state='0'
ORDER BY id DESC LIMIT 3
) t ORDER BY id ASC LIMIT 1
";
$result = mysql_query($query, $mysql);
if ( !$result ) { // query failed
die('<pre>'.htmlspecialchars(mysql_error($mysql)).'</pre><pre>'.htmlspecialchars($query).'</pre>');
}
$previousIDq = mysql_fetch_assoc($result);
if ( !$previousIDq ) {
die('empty result set');
}
else {
$previousID = $previousIDq['id'];
}
You need to separate your code to be able to debug
$query = "SELECT * FROM
(SELECT * FROM comments
WHERE postID='$id' AND state='0'
ORDER BY id DESC LIMIT 3
) t ORDER BY id ASC LIMIT 1";
$result = mysql_query($query);
echo mysql_error(); //what eror comes out here
while($previousIDq = mysql_fetch_assoc($result))
{
print ($previousIDq['id']);
}
NOTE: mysql_* is depreciated, upgrade to mysqli or PDO
Please stop using mysql_ functions to write new code, it is being deprecated. Use mysqli_ or PDO functions (mysqli below).
Bind your parameters to prevent SQL injection
Always use a column list (don't use SELECT *)
If you're returning > 1 row, use a while loop
mysqli_ solution
$link = mysqli_connect("localhost", "user_name", "password", "stock");
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
$stmt = mysqli_prepare($link, "SELECT t.id FROM
(SELECT id FROM comments
WHERE postID = ? AND state = 0
ORDER BY id DESC
LIMIT 3) t
ORDER BY id ASC");
mysqli_bind_param($stmt, 's', $id) or die(mysqli_error($dbh));
$result = mysqli_stmt_execute($stmt) or die(mysqli_error($link));
while($row = mysqli_fetch_assoc($result)) {
echo $row[id];
}
mysqli_close($link);
mysql_ solution
$stmt = "SELECT t.id FROM
(SELECT id FROM comments
WHERE postID = $id AND state = 0
ORDER BY id DESC
LIMIT 3) t
ORDER BY id ASC";
$result = mysql_query($stmt) or die(mysql_error());
$row = mysql_fetch_assoc($result);
while($row = mysql_fetch_assoc($result)) {
echo $row[id];
}

Mysql_query error

I have one problem with this mysql_query:
$selectNewsComments = mysql_query("
SELECT user_id, comment, time_add
FROM news_comments
ORDER BY id DESC
LIMIT " .($pageNum - 1) * $numberOfNewsInPage . ", ".$numberOfNewsInPage."
WHERE news_id = '".$nid."'
") or die(mysql_error());
That is error message:
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 'WHERE news_id = '18'' at line 1
Can someone tell me from whear come this proble?
Your ORDER BY id DESC LIMIT should go after the WHERE
Warning: The question's sample code uses PHP's mysql extension, which
was deprecated in PHP 5.5.0 and removed entirely in PHP 7.0.0.
The WHERE clause should go before ORDER BY.
mysql_query("SELECT user_id, comment, time_add FROM news_comments WHERE news_id = '".$nid."'ORDER BY id DESC LIMIT " .($pageNum - 1) * $numberOfNewsInPage . ", ".$numberOfNewsInPage)
use this instead
$selectNewsComments = mysql_query("
SELECT user_id, comment, time_add
FROM news_comments
LIMIT " .($pageNum - 1) * $numberOfNewsInPage . ", ".$numberOfNewsInPage."
WHERE news_id = '".$nid."'
ORDER BY id DESC
") or die(mysql_error());
what i changed is :
i placed ORDER BY id DESC in the end of the query where is should be so that it works

Categories