I know that if statement gives a result as a Boolean.
<?php
if (isset($_GET['subj'])) {
$sel_subj = $_GET['subj'];
$sel_page = "";
?>
Can i use $sel_subj or $sel_page outside if statement ? The second question in the case of while loop ? Can i use a variable outside it or its considered as in the local scope ?
while ($page = mysql_fetch_array($page_set)) {
echo "<li";
if ($page["id"] == $sel_page) { echo " class=\"selected\""; }
echo "><a href=\"content.php?page=" . urlencode($page["id"]) .
"\">{$page["menu_name"]}</a></li>";
}
Basically yes, any variables defined inside an if or while will be available in the scope that the if or while exists in (as they are defined in a conditional though they might not have been set so you would receive an undefined warning)
so
function foo(){
$i=0
while($i==0){
$i=1;
$a=1;
}
echo $a;
//$a is available here although it might be undefined as the condition may not have been met
}
echo $a //$a is not available here
You should ideally declare the variable first.
Related
I need to use a variable from SQL. I can print which I wrote the variable. But I can't use
it when it out of while query.
Here is the SQL:
if ($result = $mysqli->query("SELECT * FROM organize WHERE organize.nid=$nid"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
while ($row = $result->fetch_object())
{
echo $row->nid;
echo $row->omid;
$id=$row->omid;
}
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
And the header under this scripts.
header("Refresh: 10;http://localhost/records.php?mid= $id ");
I know this is not right way. But I show you what I want. Need to use that 'omid' in header inseat of '$id'.
Finally I resolved it. This scripts like the above codes. I didn't understand why It didn't work. Maybe because I should not use
echo $row->nid;
echo $row->omid;
or
$id=$row->omid;
The right usage is as follows:
while ($row = $result->fetch_object())
{
$dd=$row->omid;
}
header("Refresh: 2;http://localhost/records.php?mid= $dd");
I'm having problems in understanding a part of the meaning of binding certain variable types in PDO and mysqli if the type given, in my case, seems to be meaningless. In the following code, the type bound (like i or s) gets ignored. The table row "wert_sortierung" in the database is INT(11). Regardingless if $val_int is really integer or not and if I bind it via i,s / PDO::PARAM_INT or _STR, the query always works, no break, no error or warning, that the types in the binding and database or variable itself don't fit.
<?
class PDOTest {
protected $pdo;
function __construct(){
$usr="usr";
$pwd="pwd";
$host="localhost";
$db="db";
$val_int="I'm a string";
$val_str="OP";
$querystring="SELECT wert_langtext FROM TB_wert WHERE wert_sortierung = ? AND wert_CD = ?";
try {
$db_info = "mysql:host=$host;dbname=$db"; // usually provided via require_once and during construction
$this->pdo = new PDO($db_info, $usr, $pwd);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $this->pdo->prepare($querystring);
$stmt->bindValue(1,$val_int,PDO::PARAM_INT);
$stmt->bindValue(2,$val_str,PDO::PARAM_STR);
$stmt->execute();
$row_return = $stmt->fetchAll(PDO::FETCH_ASSOC);
$this->varprint($row_return);
$this->pdo = NULL;
}
catch (PDOException $ex) {
printf ('Es spricht:');
$this->printerror("Fehla! (" . $ex->getMessage() . ")");
$this->pdo = NULL;
exit();
}
printf("<br />-------<br />");
//Added for comparison
$mysqli = new mysqli($host, $usr, $pwd, $db);
$m_stmt = $mysqli->prepare($querystring);
$m_stmt->bind_param('is',$val_int, $val_str);
$m_stmt->execute();
$m_stmt->bind_result($row_return);
$m_stmt->fetch();
$this->varprint($row_return);
$m_stmt->close();
$mysqli->close();
}
private function printerror($txt) {
printf("<p><font color=\"#ff0000\">%s</font></p>\n",
htmlentities($txt));
}
private function varprint($var) {
echo "<br />";
echo "<pre>";
echo var_dump($var);
echo "</pre>";
}
}
new PDOTest();
?>
Please can anyone point out my error in reasoning.
It is actually Mysql's loose-typing that that deceived you.
As a matter of fact, regular Mysql queries can accept strings for the numberic values all right:
SELECT wert_langtext FROM TB_wert WHERE wert_sortierung = '1' AND wert_CD = '1';
while prepared statement just following this behavior.
However, a contrary situation is not that harmless. Addressing a string value with a number
SELECT wert_langtext FROM TB_wert WHERE wert_sortierung = 1;
will cause infinite number of warnings in case of wert_sortierung being of string type and some unexpected behavior, like matching for ALL the rows.
So, as a general advise I would suggest to always use 's' by default. The only drawback is PDO's emulated prepares and it can be easily worked around.
So, to answer your question explicitly - prepared statements just allow the same behavior as regular queries, adding nothing to it. Everything that possible with a regular query, is possible with prepared statement as well. And no, binding do not validate your data (however it should. Imn my class I test integer placeholders and throw an exception if no numeric value given)
function mysql_insert($data_array){
$sql = "insert into `". $this->table_name. '`';
$array_keys = array_keys($data_array);
$array_keys_comma = implode(",\n", preg_replace('/^(.*?)$/', "`$1`", $array_keys));
for($a=0,$b=count($data_array); $a<$b; $a++){ $question_marks .="?,"; }
$array_values = array_values($data_array);
$array_values_comma = implode(",", $array_values);
$sql.= " ($array_keys_comma) ";
$sql.= " values(". substr($question_marks, 0,-1) .")";
$prepare = $this->connDB->prepare($sql);
$insert = $prepare->execute(array($array_values_comma));
}
I want to creat like this universal functions, $data_array-comes from $_POST
This function will work for all form. But i dont know what is my wrong :S
I don't know what is my wrong
That's quite easy to know: number of bound variables does not match number of tokens.
I want to creat like this universal functions, $data_array-comes from $_POST
Here you go: Insert/update helper function using PDO
$array_values_comma is a scalar after you implode() the array. So you always pass an array of one element to your execute() function. You should pass $array_values.
Here's how I'd write this function:
function mysql_insert($data_array){
$columns = array_keys($data_array);
$column_list_delimited = implode(",",
array_map(function ($name) { return "`$name`"; }, $columns));
$question_marks = implode(",", array_fill(1, count($data_array), "?"));
$sql = "insert into `{$this->table_name}` ($column_list_delimited)
values ($question_marks)";
// always check for these functions returning FALSE, which indicates an error
// or alternatively set the PDO attribute to use exceptions
$prepare = $this->connDB->prepare($sql);
if ($prepare === false) {
trigger_error(print_r($this->connDB->errorInfo(),true), E_USER_ERROR);
}
$insert = $prepare->execute(array_values($data_array));
if ($insert === false) {
trigger_error(print_r($prepare->errorInfo(),true), E_USER_ERROR);
}
}
A further improvement would be to do some validation of $this->table_name and the keys of $data_array so you know they match an existing table and its columns.
See my answer to escaping column name with PDO for an example of validating column names.
I kwnow that using an ORM like Doctrine2 for building queries is safe, meaning that parameters are escaped by default.
But i'm guessing that this is not so obvious when using literals and when this literal comes directly from the query string:
$builder = $this->getRepository()->createQueryBuilder('e');
$request = $this->getRequest();
// Loop each allowed filter field and check if exists in $request
foreach($this->getFilterFields() as $filter) :
// Skip falsy values in $request
if(!$value = $request->get($filter)) continue;
// Add OR LIKE %$value% where $value is GET paramter
$like = $builder->expr()->literal("%$value%");
$builder->orWhere($builder->expr()->like("e.$filter", $like));
endforeach;
Should safety be improved in some way?
$queryBuilder->expr returns an ExpressionBuilder object. Inside ExpressionBuilder we find:
public function literal($input, $type = null)
{
return $this->connection->quote($input, $type);
}
So literals do get quoted and should be fine to use.
We also find:
public function like($x, $y)
{
return $this->comparison($x, 'LIKE', $y);
}
public function comparison($x, $operator, $y)
{
return $x . ' ' . $operator . ' ' . $y;
}
$y is fine because it goes through literal first. Do want to be a bit careful about $x. As long as your filterFields are internal then no problem. If they are coming from the user then you need to make sure they are valid.
I want to test to see if a variable has been assigned a variable and if not perform action. How can this be achieve?
I've attempted it with the following code but receive the error: The right operand of '-is' must be a type.
$ProgramName is not assigned at this point.
If ($ProgramName -isnot $null) {
$ProgramName = $ProgramName + ', ' + $cncPrograms
}
Else {
If ($cncPrograms -isnot $null) {
$ProgramName = $cncPrograms
}
}
Any unassigned variable will have a value of null, not a data type of null. So, just do this:
If ($ProgramName -ne $null)
...that will return TRUE if it's been assigned to a non-null value.
An even easier check to make is
IF($ProgramName)
Which will check if that is $null or not, though the logic is reversed, so you could use
IF(!$ProgramName)
Edit:
Ruffin raises a good point about strictmode in comments. This method will work as well:
Test-Path variable:ProgramName or Test-Path variable:global:ProgramName if it's explicitly global scoped, for instance. This will return $true or $false depending on if the variable exists.
Test-Path variable:\var should do what you want, I guess.
Contrary to answers above
Test-Path variable:ProgramName
Might not be what you are looking for because it only tests for the existence of the variable. If the Variable is set to $null it will still return $true.
Therefore in strictmode you may have to test for it's existence existence and whether it is non-empty.
Set-StrictMode -version Latest
#TODO Add a scope parameter
Function IsEmpty([string]$varname){
if (Test-path "variable:$varname"){
$val=(gi "variable:$varname").value
if ($val -is [bool]) {$false}
else {$val -eq '' -or $val -eq $null} }
else{ $true }
}
#TEST:
if (test-path variable:foobar){remove-variable foobar} ; IsEmpty foobar
$foobar=$null; IsEmpty foobar
$foobar=''; IsEmpty foobar;
$foobar=$false; IsEmpty foobar
#Results:
True
True
True
False
Strict mode kind of takes some of the fun out of scripting...
To build on the (correct) answers from JNK and David, check out this great blog post from Jeffrey Snover that walks you through all the use cases of Boolean expressions in PoweShell. It concludes with how to test for the existence of a variable.
https://devblogs.microsoft.com/powershell/boolean-values-and-operators/
Aside from the fact that -isnot is for types, in powershell 7 there's a new operator for this purpose. The assignment will only happen if the left side is $null.
$programname ??= 'foo'