I am trying to retrieve one result from my database table 'members' using a prepared call.
$favid = 1;
$type = "favdeal";
$action = 1;
$user_id = 1;
$stmt = $mysqli->prepare("SELECT ? FROM members WHERE id=?");
$stmt->bind_param('ss', $type, $user_id);
$stmt->execute();
$stmt->bind_result($favs);
while ($stmt->fetch()) {
print($favs);
}
$stmt->close();
This is the only way i managed to get any kind of result.
The table has a column called 'favdeal' which has a value of '2' in it.
The result printed returns the name of the column not the value.
So my question is how do i get the value '2' instead of the name of the column?
You can't bind columns (or tables) from doing a SELECT as you have in SELECT ?.
Select an actual column.
Or, if you want to do it dynamically, you need to use a variable.
Example: SELECT $type <= that is allowed.
However, column names can be binded when using a WHERE clause.
Example: SELECT column FROM table WHERE column=?
which you are presently using => WHERE id=?
Consult the manual on bind_param()
http://www.php.net/manual/en/mysqli-stmt.bind-param.php
Footnotes:
If you happen to use an MySQL reserved word (it could happen), you will need to wrap your column's variable with backticks.
For example: (if using $type="from";) "from" being a reserved word.
SELECT `$type` FROM members WHERE id=?
For a list of MySQL reserved words, visit the following page:
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Related
I want to find out how many rows in a table of my database meet a certain rule, specifically that "category" matches another variable and "published" is today or earlier. Then I want to simply echo that number.
I have no idea how to go about doing this, though.
I thought I could use count() but I'm not sure how to call just a single column and put the results of each row in an array.
Thanks!
Do this using SQL:
Try this in your database (your columns/tables may be different):
SELECT count(*) FROM blog_posts WHERE category = 'hot_stuff' and published <= NOW();
Then to execute this in PHP, depending on your framework and connection to the database:
$myCategory = 'hot_stuff';
$myTable = 'blog_posts';
$sql = "SELECT count(*) FROM {$myTable} WHERE category = '{$myCategory}' and published <= NOW();";
$rowCount = $db->query($sql);
echo $rowCount;
Connect to your database.
$pdo = new PDO($dsn, $user, $password);
Create a prepared statement. This is essential because you need to pass a value for category from your application to the query. It is not necessary to pass a value for the current date because the database can provide that for you. The ? is a placeholder where the parameter you pass will be bound.
$stmt = $pdo->prepare("SELECT COUNT(*) FROM your_table
WHERE category = ? AND published <= CURDATE()");
Do not concatenate the parameter into your SQL string (like WHERE category = '$category') because this will create an SQL injection vulnerability.
Execute the prepared statement using your specified value for category.
$stmt->execute([$category]); // assuming you have already defined $category
Use fetchColumn to return a single value, the count of rows that matched your criteria.
echo $stmt->fetchColumn();
I'm building a QueryBuilder where you can insert dynamically, after that I would like to return the last row inserted, so far I'm getting the last inserted Id with pdo.
$last_id = $this->pdo->lastInsertId();
After that i need to do a query
$statement = $this->pdo->prepare("SELECT * FROM {$table_name} WHERE id = :id");
The problem is that my column
Id
Doesn't call like that all the time, sometimes it name is id_user or id_work, etc.
What i need is to get the column name of where PDO is getting the last Id.
No direct way to know the field name, and there are two solutions.
1) If less tables, you can build an array to save the "id" field directly. for example :
$tables = ["table_1" : "id_user", "table_2" : "id_work"]
and you can use the $tables[$table_name] instead of the id in your SQL.
2) If you don't know which tables will be used, you can analysis the table directly via PDO before you generate the query sql.
For example
$stmt = $pdo->prepare('DESC tablename');
$stmt->execute();
$table_fields = $stmt->fetchAll(PDO::FETCH_COLUMN);
foreach($table_fields as $field){
if($field["Extra"] == "auto_increment"){
$field_id_name = $field["Field"];
break;
}
}
This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Closed 6 years ago.
I've got a little question. I want to get specific information out of my database via mysqli query:
public function get_searchorder_single_information($soid, $information) {
global $mysqli;
$stmt = $mysqli->prepare("SELECT ? FROM pr_hr_searchorders WHERE id = ?");
$stmt->bind_param('si', $information, $soid);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
echo $result;
$stmt->close();
}
In my example, $information is set 'job', but it can have other values, too (e.g. 'salary'). When I try to use my query with this variable, echo outputs just 'job' and not the value that is saved in my database. When I write 'job' instead of the '?', echo outputs the correct value.
So now I could make a function for each information I search, but this would end in spaghetti code. So I ask you if there is any possibility to use my search query like above with correct output. How would I do that?
Thanks in advance and sorry for my bad english writing.
Read documentation : http://php.net/manual/en/mysqli.prepare.php
The markers are legal only in certain places in SQL statements. For
example, they are allowed in the VALUES() list of an INSERT statement
(to specify column values for a row), or in a comparison with a column
in a WHERE clause to specify a comparison value. However, they are not
allowed for identifiers (such as table or column names), in the select
list that names the columns to be returned by a SELECT statement, or
to specify both operands of a binary operator such as the = equal
sign. The latter restriction is necessary because it would be
impossible to determine the parameter type. It's not allowed to
compare marker with NULL by ? IS NULL too. In general, parameters are
legal only in Data Manipulation Language (DML) statements, and not in
Data Definition Language (DDL) statements.
Modify your code :
$stmt= $mysqli->prepare("SELECT $information FROM pr_hr_searchorders WHERE id = ?");
$stmt->bind_param('i', $soid);
Change your code to
public function get_searchorder_single_information($soid, $information) {
global $mysqli;
$query = "SELECT".$information." FROM pr_hr_searchorders WHERE id = ?"
$stmt = $mysqli->prepare($query);
$stmt->bind_param('si', $soid);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
echo $result;
$stmt->close();
}
Then you will get the desired result
SOLVED: Reason Can I parameterize the table name in a prepared statement?
I have a very simple Query to collect data from a two column table in MySQL. Normally it worked but for some reason I know receive the error: Undefined offset: 1
$query_select = ("SELECT ?, ? FROM _HOOFDRUBRIEK");
$stmt = $mysqli->prepare($query_select);
$stmt->bind_param("ss", $column1, $column2);
$stmt->execute();
$stmt->store_result();
//$count = $stmt->num_rows;
//echo $count;
/die();
$stmt->bind_result( $key_hoofdrubriek ,
$descr_hoofdrubriek );
$stmt->fetch();
$hoofdrubriek[] = array('key' =>$key_hoofdrubriek ,
'descr' =>$descr_hoofdrubriek );
//Here I request the variable, what occurs the error
$var = $hoofdrubriek[1]['descr'];
echo 'Show here what's in the var: '.$var ;
Does anyone know why I get this error, because from my point of view, a multidimensional array can be called by $array_name[row][column];
You are mistinpreting how that works. Result bind parameters are just bound in order to the selected field. You still need to select normal fields as usual.
Moreover, you cannot specify field names as input parameters. In your situation, you select two constant values, namely the strings you pass as input parameters. This is why you get the field names in the result instead of the values of those fields. The parameters are just string values, so the query that is executed would look like this:
SELECT 'key_hoofdrubriek', 'descr_hoofdrubriek' FROM FROM RGS_HOOFDRUBRIEK
So, skip the question marks and the input bind parameters altogether and build the query like so:
$query_select = ("SELECT key_hoofdrubriek, descr_hoofdrubriek FROM RGS_HOOFDRUBRIEK");
Or, if you must, by using PHP variables in the statement:
$query_select = ("SELECT $column1, $column2 FROM RGS_HOOFDRUBRIEK");
For reading, you can of course still use bind_result.
You can't use placeholders for column names, they're always treated as expressions. So your prepared query is equivalent to writing:
SELECT 'key_hoofdrubriek', 'descr_hoofdrubriek' FROM RGS_HOOFDRUBIEK
This just returns those literal strings for each row in the table, not the values in the columns with those names.
If you need to determine the column names dynamically, you have to use variable substitution or concatenation, you can't use placeholders:
$query_select = "SELECT $column1, $column2 FROM RGS_HOOFDRUBRIEK";
$stmt = $conn->prepare('select count(names) as names from names where names = :name');
$stmt->bindParam(':name', $name);
$stmt->execute();
How do I output the value of names when doing a select count() using PDO without having to use a while loop or something similar?
I need the count value of names (1, 3 or 5 or whatever it is).
$count = $stmt->fetchColumn();
fetchColumn()
The select count(..) from ..-Statement always only outputs this column (the count of rows), so you cannot access the names. You will have to execute a statement only for getting the names, OR you can actually output the name by yourself, because you already have it in $name ;)