public function get_modno_sno($id)
{
$query = 'select a.model_no,a.serial_no,a.stock_id from tra_item_stock a where a.trans_id is NULL and a.model_no = '.$id.'
union
select a.model_no,a.serial_no,a.stock_id from tra_indent_issue_details_2 a where a.flag = 3 and a.model_no ='.$id;
$result = $this->db->query($query);
return $result->result();
}
When I run this query error displayed as:
column "kb234" does not exist
kb234 is character varying value passed to $id
You do not surround kb234 with quotes, so the database identifies it as a column name.
You could modify you code to include the quotes:
public function get_modno_sno($id)
{
$query = "select a.model_no,a.serial_no,a.stock_id from tra_item_stock a where a.trans_id is NULL and a.model_no = '$id'
union
select a.model_no,a.serial_no,a.stock_id from tra_indent_issue_details_2 a where a.flag = 3 and a.model_no = '$id'";
$result = $this->db->query($query);
return $result->result();
}
Note, however, that creating SQL queries by using string manipulation is a dodgy practice, that leaves your code vulnerable to SQL injection attacks. You should consider using a prepared statement.
.model_no ='.$id;
is missing an ' at the end for the union query
Related
Here's The code we have tried so far.
What actually we have to do is user will input data in his selected textboxes. we want php query to combine the search result and provide output.
$query=array();
$query[] = empty($_POST['keyword_s_dec']) ? : 'cand_desc='.$_POST['keyword_s_dec'];
$query[] = empty($_POST['keyword_s_location']) ? : 'cand_location='.$_POST['keyword_s_location'];
$results = implode('AND', $query);
$sql = "SELECT * FROM candidate where '".$results."'";
$result = mysql_query($sql) or die(mysql_error());
Where keyword_s_dec & keyword_s_location are our texfield ID;
cand_desc & cand_location are database columns.
Also we are trying for SQL Injection how can we achieve this?
I did some adjustments to your code:
$query = array();
if (!empty($_POST['keyword_s_dec'])) $query[] = "cand_desc = '".$_POST['keyword_s_dec']."'";
if (!empty($_POST['keyword_s_location'])) $query[] = "cand_location = '".$_POST['keyword_s_location']."'";
$condition = implode(' AND ', $query);
$sql = "SELECT * FROM candidate WHERE $condition";
$result = mysql_query($sql) or die(mysql_error());
This builds a valid query:
SELECT * FROM candidate WHERE cand_desc = 'test1' AND cand_location = 'test2'
Your main issue was that you weren't inserting spaces around the AND string and single quotes for the values in the WHERE clause, but I also removed the conditional ?: operator since it made the code less readable.
Note that I only fixed the code that you wrote. It won't work if none of the POST variables are set (since then the SQL string will have a WHERE clause without any content) and you should definitely use mysql_real_escape_string() when reading the POST variables to prevent SQL injection.
Can you explain me why my code isnt working? Ive been thinking about it for a while and I cant find it. obviously I want to print some columns from rows where column F1 is equal to user's username.
$db = JFactory::getDBO();
$user = JFactory::getUser();
$query = "SELECT * FROM qwozh_visforms_1 WHERE F1 = ".$user->username;
$db->setQuery($query);
$result = $db->query();
while($row = mysqli_fetch_object($result))
{
print $row->F1;
}
It works when I remove condition from select command and I cant figure out how to make it work with it
$query = "SELECT * FROM qwozh_visforms_1";
Now Im getting this error:
UNKNOWN COLUMN 'ADMIN' IN 'WHERE CLAUSE' SQL=SELECT * FROM
QWOZH_VISFORMS_1 WHERE F1 = ADMIN RETURN TO PREVIOUS PAGE
Thanks
All it takes if a quick read of the Joomla documentation. The following is the same as your query but making full use of Joomla's up to date database class:
$db = JFactory::getDbo();
$user = JFactory::getUser();
$query = $db->getQuery(true);
$query->select(array('*'))
->from($db->quoteName('#__visforms_1'))
->where($db->quoteName('F1') . ' = '. $db->quote($user->username));
$db->setQuery($query);
$results = $db->loadObjectList();
// Display the results
foreach($results as $result){
// echo what you want here
}
Note, I've used the prefix #__ rather than manually defining qwozh, assuming your table belong to a Joomla extension.
I know PHP and MySQL, but not Joomla. But the problem is that your username needs to be quoted because it is probably a string.
Try this:
$query = "SELECT * FROM qwozh_visforms_1 WHERE F1 = '{$user->username}'";
or
$query = "SELECT * FROM qwozh_visforms_1 WHERE F1 = ".$db->quote($user->username);
You need to wrap the name in quotes:
$query = "SELECT * FROM qwozh_visforms_1 WHERE F1 = '".$user->username . "'";
As pointed out in the comments my answer has a pretty bad quality, you may want to look at prepared statements, expecially using bindParam, which takes care of quotes for you and protects you agains SQL injection attacks.
Unfortunately I cannot suggest you Joomla based approach since I never used it, somebody else can suggest you a more appropriate solution.
I get error : "Unknown column 'Array' in 'where clause'" perharps from variable $query in my code.
This is my code :
$zzz = mysql_query("SELECT alias FROM table WHERE ColumnA = 'yes'");
while($aaa = mysql_fetch_array($zzz)){
$array[] = $aaa['alias'];
}
$query = mysql_query("SELECT * FROM table2 WHERE alias NOT IN ($array) ORDER BY Column1 DESC, Column2 DESC");
I want to make a SELECT query WHERE 'alias' in table2 not equal to any data in $array which come from fetch array $aaa.
I got a clue to make an array from fetch array from :
Array in SQL Query?
But, i don't know how to add 'quote' for each data in array that made from $aaa.
Could anyone tell me how to do this? :)
Why not use nested queries? Example:
$query = mysql_query("SELECT * FROM table2 WHERE alias NOT IN (SELECT alias FROM table WHERE ColumnA = 'yes') ORDER BY Column1 DESC, Column2 DESC");
As noted in my below comment, however, your interaction appears to be vulnerable to injection attacks. This can be avoided to some degree, as others have stated, but as I have also stated, one of the better ways is to use PDO. Example:
try {
$dbh = new PDO("mysql:host=localhost;dbname=dbname", "user", "password");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("SELECT * FROM table2 WHERE alias NOT IN (SELECT alias FROM table WHERE ColumnA = :bool) ORDER BY Column1 DESC, Column2 DESC");
$stmt->bindValue(":bool","yes");
$stmt->execute();
} catch (\PDOException $e) {
// Something went wrong
}
while ($row = $stmt->fetch()) {
// do stuff with query
}
PDO ships with php 5.1.
You're trying to use $array directly, and it does not print itself the way you need to. Following the advice in the linked question, you could use implode:
$newarray = implode(", ", $array);
$query = mysql_query("SELECT * FROM table2 WHERE alias NOT IN ($newarray) ORDER BY Column1 DESC, Column2 DESC");
As for adding quotes, you can just concatenate them together. However, I'd also escape the values before quoting, to avoid SQL injection vulnerabilities:
while($aaa = mysql_fetch_array($ambilLarikAkunTerlindungi)){
$array[] = "'" . mysqli_real_escape_string($aaa['alias']) . "'";
}
Is it possible to re-write the code below, maybe even with an if (result > 0) statement, in just one line (or simply shorter)?
// a simple query that ALWAYS gets ONE table row as result
$query = $this->db->query("SELECT id FROM mytable WHERE this = that;");
$result = $query->fetch_object();
$id = $result->id;
I've seen awesome, extremely reduced constructs like Ternary Operators (here and here - btw see the comments for even more reduced lines) putting 4-5 lines in one, so maybe there's something for single result SQL queries like the above.
You could shorten
$query = $this->db->query("SELECT id FROM mytable WHERE this = that;");
$result = $query->fetch_object();
$id = $result->id;
to
$id = $this->db->query("SELECT id FROM mytable WHERE this = that")->fetch_object()->id;
but this, and the original code will emit errors, if any of the functions returns an unexpected response. Better to write:
$query = $this->db->query("SELECT id FROM mytable WHERE this = that");
if (!$query) {
error_log('query() failed');
return false;
}
$result = $query->fetch_object();
if (!$result) {
error_log('fetch_object() failed');
return false;
}
$id = $result->id;
function get_tags_by_criteria($gender_id, $country_id, $region_id, $city_id, $day_of_birth=NULL, $tag_id=NULL, $thread_id=NULL) {
$query = "SELECT tags.*
FROM tags, thread_tag_map, threads
WHERE thread_tag_map.thread_id = threads.id
AND thread_tag_map.tag_id = tags.id
AND threads.gender_id = $gender_id
AND threads.country_id = $country_id
AND threads.region_id = $region_id
AND threads.city_id = $city_id
AND tags.id LIKE '%$tag_id%'
AND threads.id LIKE '%$thread_id%'";
if(!$day_of_birth)
{
$query += "AND threads.min_day_of_birth <= '$day_of_birth AND threads.max_day_of_birth >= '$day_of_birth' ";
}
$query += "GROUP BY tags.name";
$result = $this->do_query($query);
return $result;
}
if no $day_of_birth is passed as an argument i want the sql to omit the 2 lines inside the if. i used:
$all_tags = $forum_model->get_tags_by_criteria(1, 1, 0, 0);
i wonder why this sql returns a error:
Couldn't execute query: 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' at line 1
You're using the addition (+=) operator when you should be using the concatenation (.=) operator.
You should be escaping your inputs too, to avoid SQL injection - see mysql_real_escape_string()
there's missing white space between " and AND in appended string
Your problem is that you left out a ' by the date of birth.
Change it to AND threads.min_day_of_birth <= '$day_of_birth' (Note closing ' and opening )
Also, as others have pointed out, you should write $query .= instead of $query +=
(note .)
You have a SQL Injection vulnerability; you should use parameters.
Remember Bobby Tables!
.= is used for string concatenation in PHP, not +=
You can also use placeholders in your query. If an option/parameter is set the script sets the contents of the placeholder to the appropriate sql code otherwise the placeholder is empty/null.
e.g.
function get_tags_by_criteria($gender_id, $country_id, $region_id, $city_id, $day_of_birth=NULL, $tag_id=NULL, $thread_id=NULL) {
if ( !is_null($day_of_birth) ) {
$day_of_birth = "AND ('$day_of_birth' BETWEEN threads.min_day_of_birth AND threads.max_day_of_birth)"
}
$query = "
SELECT
tags.*
FROM
tags, thread_tag_map, threads
WHERE
thread_tag_map.thread_id = threads.id
AND thread_tag_map.tag_id = tags.id
AND threads.gender_id = $gender_id
AND threads.country_id = $country_id
AND threads.region_id = $region_id
AND threads.city_id = $city_id
AND tags.id LIKE '%$tag_id%'
AND threads.id LIKE '%$thread_id%'
{$day_of_birth}
GROUP BY
tags.name
";
$result = $this->do_query($query);
return $result;
}
edit: as mentioned before: keep the possible sql injection in mind.