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
Related
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);
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']) . "'";
}
I began to create a website for my small real estate business.
I played a bit with functions http://www.php.net mysql and I managed to make a page accessed via AJAX and returning html content for the search engine.
I have a database already populated with apartments and houses
The problem is that if the apartment name is "apartment" I return html content if "apartment with 3 rooms" it no longer write anything.
I do not understand where I was wrong:
<?php
$search = $_GET['selected'];
$link = mysql_connect('localhost', 'root', '');
mysql_select_db('houses', $link);
function searchHouse($search, $link){
$query = "select * from houses where name=$search limit 1";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$query2 = "select * from houses_info where house_id=$row[id]";
$result2 = mysql_query($query2);
$row = mysql_fetch_assoc($result2);
return $row;
}
$result = searchHouse($search, $link);
echo $result['house_sq'];
echo "<br>";
echo $result['house_rooms'];
echo "<br>";
echo $result['house_bathrooms'];
echo "<br>";
echo $result['house_address'];
?>
you should know if you "played" with php.net that mysql_* functions are deprecated and are no longer maintained. It's a red box on top of the page informing you that.
you have a big MySQL injection hole there, you are not escaping $string at all
your problem is that you are not adding quotes to $string like: '$string'
you should stat using PDO to get rid of the bad code and SQL Injections holes.
you can wrap those 2 selects into a single select:
<?php
function searchHouse($search, $link){
$search = mysql_real_escape_string($search);
$query = "select * from houses_info where house_id IN (select * from houses where name='".$search."' limit 1)";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
return $row;
}
?>
since you are already building that website you can start moving to PDO, read this tutorial, your code will be more like this:
<?php
$db = new PDO('mysql:host=localhost;dbname=houses;charset=UTF-8', 'root', '', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$search = $_GET['selected'];
function searchHouse($search){
global $db;
$query = $db->prepare("select * from houses_info where house_id IN (select * from houses where name=:search limit 1)");
$query->execute(array(':search' => $search));
$row = $query->fetch(PDO::FETCH_ASSOC);
return $row;
}
$result = searchHouse($search);
?>
try:
$query = "select * from houses where name='".mysql_real_escape_string($search)."' limit 1";
and remember to always sanitize user input before passing it to sql to avoid sql injections.
Your first query should be:
$query = "select * from houses where name like $search% limit 1";
Strings need to be quoted in queries. Also, this is vulnerable to MySQL injection, make sure to escape $search with mysql_real_escape_string. Or even better yet use MySQLi or PDO instead of the old mysql_ functions.
$query = "select * from houses where name=$search limit 1";
Should be:
$query = "select * from houses where name='$search' limit 1";
Although you REALLY need to escape $search because it came from a user, even if they aren't malicious, any search queries with a single quote in it will break;
$search = $_GET['selected'];
Should be:
$search = mysql_real_escape_string($_GET['selected']);
(Anybody have the copy paste handy with the links to tutorials for MySQLi/PDO and such?)
My code is here :
$array_letter = array("A","B","C","Ç","D","E","F","G","H","I","İ","J","K","L",
"M","N","O","P","R","S","Ş","T","U","Ü","V","Y","Z");
$sql = "SELECT id,city FROM city WHERE city LIKE '" .$array_letter[$i]."%'";
And after these codes :
for ($i=0;$i<27;$i++) {
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<h3>".$row['city']."</h3>";
}
}
$sql is meaningless because $array_letter[$i]will not work there. But $sql must be top of these codes for design. Because I coded switch-case statement. According to requests, $sql will change for this reason I can not write $sql under for loops. But all my queries depens on $array_letter. How can I make $array_letter work?
You should use the mysqli driver and prepared statements:
$st = $mysqli->prepare("SELECT id,city FROM city WHERE city LIKE ?'");
for ($i=0;$i<27;$i++) {
$st->bind_param("s", $array_letter[$i].'%');
$st->execute();
$result = $st->get_result();
while ($row = $result->fetch_assoc()) {
echo "<h3>".$row['city']."</h3>";
}
}
Although for this case, I would recommend just doing one big query since it looks like you are getting everything: SELECT id,city FROM city ORDER BY city...
For educational purposes, an alternative approach would be to do something like:
$sql = "SELECT * FROM foo WHERE bar='%s'";
mysql_query(sprintf($sql, "42"));
That can be useful in other situations, but again, if you are writing SQL, use prepared statements as they solve this problem more gracefully with the extra protection of helping to prevent SQL injection attacks and minimizing the amount of SQL parsing the server has to do.
You should use prepared statements, as Matthew mentioned in his answer.
Otherwise consider this (using PHP 5.3 closures):
$sql = function($i) use ($array_letters) {
return "SELECT id,city FROM city WHERE city LIKE '" .$array_letter[$i]."%'";
}
Then inside your loop:
mysql_query($sql($i));
This will help to reduce the database calls.
$array_letter = array("A","B","C","Ç","D","E","F","G","H","I","İ","J","K","L",
"M","N","O","P","R","S","Ş","T","U","Ü","V","Y","Z");
for($i=0;$i<count($array_letter);$i++){
if($i!=count($array_letter)-1)
$qstring.="city like '".$array_letter[$i]."%' or ";
else
$qstring.="city like '".$array_letter[$i]."%'";
}
$sql = "SELECT id,city FROM city WHERE ".$qstring;
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<h3>".$row['city']."</h3>";
}
What's the best way with PHP to read a single record from a MySQL database? E.g.:
SELECT id FROM games
I was trying to find an answer in the old questions, but had no luck.
This post is marked obsolete because the content is out of date. It is not currently accepting new interactions.
$id = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database_name', $link);
$sql = 'SELECT id FROM games LIMIT 1';
$result = mysql_query($sql, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
print_r($row);
There were few things missing in ChrisAD answer. After connecting to mysql it's crucial to select database and also die() statement allows you to see errors if they occur.
Be carefull it works only if you have 1 record in the database, because otherwise you need to add WHERE id=xx or something similar to get only one row and not more. Also you can access your id like $row['id']
Using PDO you could do something like this:
$db = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');
$stmt = $db->query('select id from games where ...');
$id = $stmt->fetchColumn(0);
if ($id !== false) {
echo $id;
}
You obviously should also check whether PDO::query() executes the query OK (either by checking the result or telling PDO to throw exceptions instead)
Assuming you are using an auto-incrementing primary key, which is the normal way to do things, then you can access the key value of the last row you put into the database with:
$userID = mysqli_insert_id($link);
otherwise, you'll have to know more specifics about the row you are trying to find, such as email address. Without knowing your table structure, we can't be more specific.
Either way, to limit your SELECT query, use a WHERE statement like this:
(Generic Example)
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];
(Specific example)
Or a more specific example:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE userID = 1"));
$userID = $getID['userID'];
Warning! Your SQL isn't a good idea, because it will select all rows (no WHERE clause assumes "WHERE 1"!) and clog your application if you have a large number of rows. (What's the point of selecting 1,000 rows when 1 will do?) So instead, when selecting only one row, make sure you specify the LIMIT clause:
$sql = "SELECT id FROM games LIMIT 1"; // Select ONLY one, instead of all
$result = $db->query($sql);
$row = $result->fetch_assoc();
echo 'Game ID: '.$row['id'];
This difference requires MySQL to select only the first matching record, so ordering the table is important or you ought to use a WHERE clause. However, it's a whole lot less memory and time to find that one record, than to get every record and output row number one.
One more answer for object oriented style. Found this solution for me:
$id = $dbh->query("SELECT id FROM mytable WHERE mycolumn = 'foo'")->fetch_object()->id;
gives back just one id. Verify that your design ensures you got the right one.
First you connect to your database. Then you build the query string. Then you launch the query and store the result, and finally you fetch what rows you want from the result by using one of the fetch methods.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$singleRow = mysql_fetch_array($result)
echo $singleRow;
Edit: So sorry, forgot the database connection. Added it now
'Best way' aside some usual ways of retrieving a single record from the database with PHP go like that:
with mysqli
$sql = "SELECT id, name, producer FROM games WHERE user_id = 1";
$result = $db->query($sql);
$row = $result->fetch_row();
with Zend Framework
//Inside the table class
$select = $this->select()->where('user_id = ?', 1);
$row = $this->fetchRow($select);
The easiest way is to use mysql_result.
I copied some of the code below from other answers to save time.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$num_rows = mysql_num_rows($result);
// i is the row number and will be 0 through $num_rows-1
for ($i = 0; $i < $num_rows; $i++) {
$value = mysql_result($result, i, 'id');
echo 'Row ', i, ': ', $value, "\n";
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', 'tmp', 'tmp', 'your_db');
$db->set_charset('utf8mb4');
if($row = $db->query("SELECT id FROM games LIMIT 1")->fetch_row()) { //NULL or array
$id = $row[0];
}
I agree that mysql_result is the easy way to retrieve contents of one cell from a MySQL result set. Tiny code:
$r = mysql_query('SELECT id FROM table') or die(mysql_error());
if (mysql_num_rows($r) > 0) {
echo mysql_result($r); // will output first ID
echo mysql_result($r, 1); // will ouput second ID
}
Easy way to Fetch Single Record from MySQL Database by using PHP List
The SQL Query is SELECT user_name from user_table WHERE user_id = 6
The PHP Code for the above Query is
$sql_select = "";
$sql_select .= "SELECT ";
$sql_select .= " user_name ";
$sql_select .= "FROM user_table ";
$sql_select .= "WHERE user_id = 6" ;
$rs_id = mysql_query($sql_select, $link) or die(mysql_error());
list($userName) = mysql_fetch_row($rs_id);
Note: The List Concept should be applicable for Single Row Fetching not for Multiple Rows
Better if SQL will be optimized with addion of LIMIT 1 in the end:
$query = "select id from games LIMIT 1";
SO ANSWER IS (works on php 5.6.3):
If you want to get first item of first row(even if it is not ID column):
queryExec($query) -> fetch_array()[0];
If you want to get first row(single item from DB)
queryExec($query) -> fetch_assoc();
If you want to some exact column from first row
queryExec($query) -> fetch_assoc()['columnName'];
or need to fix query and use first written way :)