PHP Add quote to array from fetch array - php

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']) . "'";
}

Related

Column order when selecting column_names in Oracle

I want display a table content along with column names.
I have used SQL query for columns
"SELECT COLUMN_NAME FROM ALL_TAB_COLUMNS WHERE TABLE_NAME = $mytable"
and I have used SQL query for content
"SELECT * FROM $mytable"
Both are working fine. Only thing is that, order of columns is different. Some times its just reverse. sometimes it is reverse with some shift of 2-3 columns depending on number of column in $mytable.
You need to include an order by when you query ALL_TAB_COLUMNS on COLUMN_ID:
"SELECT COLUMN_NAME FROM ALL_TAB_COLUMNS WHERE TABLE_NAME = $mytable ORDER BY COLUMN_ID".
This orders the columns by the order created.
Probably a better approach is to simply read the column names from the returned resultset. This means you need only one query:
$conn = oci_connect($username, $password, $connectionString);
$stmt = oci_parse($conn, 'select * from mytable');
oci_execute($stmt);
$headers = false;
while ($row = oci_fetch_assoc($stmt)) {
if (!$headers) {
// this will only output the headers on the first iteration.
print_r(array_keys($row));
$headers = true;
}
print_r($row);
}
Or you could use oci_field_name() against the resultset but I've always felt the above method is simpler.
Edit: In case there are no results, you won't be able to get the keys (since the array is empty). You can add the following code after the while loop to handle that:
if (!$headers) {
for ($i = 1; $i <= oci_num_fields($stmt); $i++) {
echo oci_field_name($stmt, $i), PHP_EOL;
}
}

PHP PDO dynamic WHERE clause

I have a simple function that returns a count from a database table, based on some criteria.
function MyCount($strTable, $strCriteria) {
$strSQL = "SELECT COUNT(*) FROM " . $strTable . " ";
if (trim($strCriteria) != "") $strSQL .= "WHERE " . $strCriteria;
$results = mysql_query($strSQL, $objConn);
$row = mysql_fetch_array($results);
return $row[0];
}
Its very useful for quickly getting a value in 1 line of code, e.g:
$Users = MyCount("Users", "Deleted = 0");
However, I'm now trying to move to PDO and am having trouble passing in the were as parametrized values. I'm trying to do something like the below (which doesn't work):
$objQuery=$objConn->prepare("SELECT count(*) as TheCount FROM :table_name WHERE :criteria");
$objQuery->bindParam(':table_name', $strTable);
$objQuery->bindParam(':criteria', $strCriteria);
I guess the obvious would be:
$objQuery=$objConn->prepare("SELECT count(*) as TheCount FROM :table_name WHERE ".$strCriteria");
$objQuery->bindParam(':table_name', $strTable);
But, this seems to go against the spirit of parametrized values... does anyone have any other suggestions?
Thanks
This line is the issue:
$objQuery->bindParam(':table_name', $strTable);
You can only bind values ( field= :value) in PDO you cannot bind table names or column names or custom dynamic where clause.
So you just build the query manually:
SELECT count(*) as TheCount FROM `$strTable` WHERE $strCriteria
function my_count($strTable, $strCriteria, $objConn)
{
$sql ="SELECT count(*) as TheCount FROM $strTable WHERE $strCriteria";
$objQuery=$objConn->query($sql);
$row =$objQuery->fetch();
return $row['TheCount'];
}
$Users = my_count("Users", "Deleted = 0", $objConn);

Pass the parameter into query

I'm new in php and PDO. I just wondering how to pass the parameter into my query,
I already assign $a="January 2010 Semester"; and to pass to my query. But when i echo the query, it display like this.
SELECT Nama,Intake,matricNo, FROM VMESubjectGrade where Intake="$a" GROUP BY Nama
It Should be display like this
SELECT Nama,Intake,matricNo, FROM VMESubjectGrade where Intake="January 2010 Semester" GROUP BY Nama
This is my code,
Hope can advise,
Special Thanks.
$a="January 2010 Semester";
mysql_select_db("school", $con);
$query2='SELECT DISTINCT(SubCode) FROM VMESubjectGrade where Intake="$a"' ;
$query2testing = mysql_query($query2);
try {
$db = new PDO('mysql:host=localhost;dbname=school;charset=utf8', 'root', 'xxx');
} catch (PDOException $e) {
echo $e->getMessage();
}
//get the SubCodes
$stmt = $db->query('SELECT DISTINCT(SubCode) FROM VMESubjectGrade where Intake="$a"');
$row_count = $stmt->rowCount();
//generate pivot sql statement
$sql = 'SELECT Nama,Intake,matricNo, ';
$dynamic_fields = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$dynamic_fields[] = $row['SubCode'];
$sql .= "MAX(CASE SubCode when '{$row['SubCode']}' then grade end) AS {$row['SubCode']}";
if ($row_count > 1) {
$sql .=',';
}
$row_count--;
}
$sql .= ' FROM VMESubjectGrade where Intake="$a" GROUP BY Nama ';
echo $sql;
THIS PROBLEM ALREADY SOLVE.
I know you think you've already solved the problem, but please read this!!
One of the main advantages to PDO is the ability to do parameterized queries, which will sanitize your database inputs. As you currently have it, you're vulnerable to SQL injection!
If someone passes a variable that you use in the query, and you don't sanitize it, you will end up in big trouble. Suppose $a was set to "; DROP TABLE VMESubjectGrade;--. What does your query become? It becomes this:
SELECT DISTINCT(SubCode) FROM VMESubjectGrade where Intake=""; DROP TABLE VMESubjectGrade;--"
The day someone tries something like this will be a very bad day for you, unless you properly sanitize your database inputs.
Try doing your queries like this:
$query = 'SELECT DISTINCT(SubCode) FROM VMESubjectGrade where Intake = :a';
$stmt = $db->prepare($query);
$stmt->execute(array(':a' => $a));
This will pass the parameter in to the query and sanitize the variable in case it actually comes from user input.
:a acts as a placeholder for a parameter in your query and you assign the value of it when you execute.
you should concact that string into query like this
echo $query2='SELECT DISTINCT(SubCode) FROM VMESubjectGrade where Intake='.$a.'';
$query2testing = mysql_query($query2);
output will be like this-> SELECT DISTINCT(SubCode) FROM VMESubjectGrade where Intake=January 2010 Semester

Include a php var result on a mysql query

It is possible to include PHP data in a MySQL result? Let me explain myself:
Two tables, one with user's actions and one with user information. I'd query the actions and retrieve the user IDs and count each one grouped by user:
$ids = $conn->fetchAll('SELECT origin,COUNT(*) as actions from action WHERE `brand` = ' . $id . ' AND SUBSTRING(origin,1,3)<>"pct" GROUP BY origin');
Then I take that result array and use it to input the user info from another table:
$norm_ids = '(';
foreach ($ids as $ids) {
$norm_ids .= $ids['origin'] .',';
}
$norm_ids = substr_replace($norm_ids ,"",-1) .')';
$users = $conn->fetchAll('SELECT * from userinfo WHERE `id` in ' . $norm_ids . ' ORDER BY `name`');
I want in $users to include the COUNT(*) I got in the previous query, is that possible directly on the query?
I have made my own script, i guess this is what you are looking for:
$sql = "SELECT * FROM user WHERE Username = '".$_SESSION['Username']."' ";
$stm = $db->prepare($sql);
$result = $stm->execute(array());
while($row = $stm->fetch(PDO::FETCH_ASSOC)) {
$userid = $row['UserID'];
}
here i get the users id
$sql = "SELECT activity.*"."FROM user_activity, activity "."WHERE user_activity.ActivityID = activity.ActivityID AND user_activity.UserID = '".$userid."' " ;
and here u use the $userid in my query.
You can use a mysql join for that:
SELECT u.*, count(a.origin) FROM userinfo AS u LEFT JOIN action AS a ON a.origin = u.id WHERE a.brand = '.$id.' AND SUBSTRING(a.origin,1,3) <> "pct" GROUP BY a.origin
You'll have to try and tweak it a little bit (probably) but it might make your script a lot easier. (I'm not sure whether userinfo will be grouped together too or not(probably shouldn't)).
When using a JOIN you'll have to set correct indexes for maximum performance though.
First of all, a few comments on the code in general:
foreach ($ids as $ids)
This just looks wrong, I don't know how PHP handles this but probably not as you would expect it. Use a different variable name, just for clarity's sake.
You need to escape the quotes around "pct" in the query so they're not parsed by PHP.
Also, I don't know where the $id comes from in the first SQL statement, but you might want to escape it. Using PDO:
$stmt = $conn->prepare("SELECT origin,COUNT(*) as actions from action WHERE `brand` = :id AND SUBSTRING(origin,1,3)<>\"pct\" GROUP BY origin");
$stmt->execute( array( ":id" => $id ) );
$ids = stmt->fetchAll();
To access the COUNT(*) data and add it to the user info, I'ld first rename it in the first query (don't like special characters in my array keys):
"SELECT origin,COUNT(*) as nummatches as actions from action WHERE `brand` = :id AND SUBSTRING(origin,1,3)<>\"pct\" GROUP BY origin"
Then, you can add it to the SELECT part of your statement in the second query:
'SELECT *,' . $ids['nummatches'] . ' from userinfo WHERE `id` in ' . $norm_ids . ' ORDER BY `name`'

What would be the most efficient way to SELECT, then DELETE this immediately

What would be the most efficient way to SELECT this, then DELETE it immediately.
SELECT * from `usersOnline` WHERE timestamp>NOW()-INTERVAL 5 SECOND ORDER BY rand() LIMIT 1;
How could I take this same select query, but also make it delete what it selected in the most efficient way?
$query = 'SELECT * FROM `usersOnline` WHERE timestamp>NOW()-INTERVAL 5 SECOND ORDER BY rand() LIMIT 1;';
$result = mysql_query($query);
$record = mysql_fetch_assoc($result);
$query = 'DELETE FROM `usersOnline` WHERE id = ' . $record['id'];
mysql_query($query);
with mysql, you would have to do one and then the other. you would use the key from the select result to then delete that record directly afterwards. in this example, i am assuming your primary key column is named "id". you would replace the myssql functions with whichever method you are using to access the database of course.
you can do like this nested query
DELETE
FROM SomeTable
WHERE EXISTS
(SELECT * from `usersOnline` WHERE timestamp>NOW()-INTERVAL 5 SECOND ORDER BY rand() LIMIT 1;
)
thanks
use DELETE FROM: http://dev.mysql.com/doc/refman/5.0/en/delete.html
I know this example mixed prepared statments with regular statements. But it's up to the developer how to write the code. This is just a proof of concept, kept simple for easy reading.
$mysqli = new mysqli('localhost', 'user', 'password', 'userTable');
$result = $mysqli->query("SELECT * from `usersOnline` WHERE timestamp>NOW()-INTERVAL 5 SECOND ORDER BY rand() LIMIT 1");
$stmt = $mysqli->prepare("DELETE FROM 'usersOnline WHERE id = ?");
while ($row = mysql_fetch_assoc($result)) {
$stmt->bind_param('i', $row["id"]);
$stmt->execute();
}
$stmt->close();
$mysqli->close();

Categories