PHP if condition not working [duplicate] - javascript

This question already has answers here:
boolean variable values in PHP to javascript implementation [duplicate]
(3 answers)
Closed 8 years ago.
I am having some problems with setting the value of "swimsuit" variable as defined below, however when I set the value to "1" in my MYSQL database, it sets $real=true but elsewise it says "real is undefined".
$query4 = "SELECT swimsuit FROM player_equipment WHERE player_name='xhyderz'";
$result = mysql_query($query4,$link);
$row = mysql_fetch_assoc($result);
$swim = $row['swimsuit'];
$real=null;
if($swim==0){
$real=false;
}else{
$real=true;
}
echo "<script type='text/javascript'> var swimsuit=".$real."; </script>";

When you concatenate a boolean variable with a string like that, you get the following:
var_dump(true . ""); // "1"
var_dump(false . ""); // ""
So if $real is false, your JavaScript looks like:
var swimsuit=;
You can either use the strings "true" or "false" for $real, or you can use json_encode:
echo "var swimsuit=" . json_encode($real) . ";";

Try :
if($swim==0){
$real="false";
}else{
$real="true";
}
Edit:
Look at cbuckley's explaination, way more clear and complete than mine.

Related

How can I convert one value from int to string within an array [duplicate]

This question already has answers here:
Converting an integer to a string in PHP
(15 answers)
Closed 8 months ago.
enter image description hereI want to make my chart data.addColumn ('string', 'hour'); must be a string.
In my request it is an int.
$temp_array = array();
while($row = mysqli_fetch_assoc($result))
{
$temp_array = array(strval($row["hour"]), $row["min"], $row["max"], $row["Avg"]);
}
result now: "["6","30.0","30.0","30.0"]"
want only the first one("6") between quotes.
php code
javascript
Use the strval() to convert integer value to string. For example:
$temp_array[] = array( strval($row["hour"]), strval($row["min"]));
$temp_array = array();
while($row =mysqli_fetch_assoc($result))
{
$temp_array[] = array( (string)$row["hour"], $row["min"], $row["max"], $row["Avg"]);
}
strval($row["hour"]) should do the trick.

Detect specific info from variable [duplicate]

I have an HTML form field $_POST["url"], having some URL strings as the value.
Example values are:
https://example.com/test/1234?email=xyz#test.com
https://example.com/test/1234?basic=2&email=xyz2#test.com
https://example.com/test/1234?email=xyz3#test.com
https://example.com/test/1234?email=xyz4#test.com&testin=123
https://example.com/test/the-page-here/1234?someurl=key&email=xyz5#test.com
etc.
How can I get only the email parameter from these URLs/values?
Please note that I am not getting these strings from the browser address bar.
You can use the parse_url() and parse_str() for that.
$parts = parse_url($url);
parse_str($parts['query'], $query);
echo $query['email'];
If you want to get the $url dynamically with PHP, take a look at this question:
Get the full URL in PHP
All the parameters after ? can be accessed using $_GET array. So,
echo $_GET['email'];
will extract the emails from urls.
Use the parse_url() and parse_str() methods. parse_url() will parse a URL string into an associative array of its parts. Since you only want a single part of the URL, you can use a shortcut to return a string value with just the part you want. Next, parse_str() will create variables for each of the parameters in the query string. I don't like polluting the current context, so providing a second parameter puts all the variables into an associative array.
$url = "https://mysite.com/test/1234?email=xyz4#test.com&testin=123";
$query_str = parse_url($url, PHP_URL_QUERY);
parse_str($query_str, $query_params);
print_r($query_params);
//Output: Array ( [email] => xyz4#test.com [testin] => 123 )
As mentioned in another answer, the best solution is using parse_url().
You need to use a combination of parse_url() and parse_str().
The parse_url() parses the URL and return its components that you can get the query string using the query key. Then you should use parse_str() that parses the query string and returns
values into a variable.
$url = "https://example.com/test/1234?basic=2&email=xyz2#test.com";
parse_str(parse_url($url)['query'], $params);
echo $params['email']; // xyz2#test.com
Also you can do this work using regex: preg_match()
You can use preg_match() to get a specific value of the query string from a URL.
preg_match("/&?email=([^&]+)/", $url, $matches);
echo $matches[1]; // xyz2#test.com
preg_replace()
Also you can use preg_replace() to do this work in one line!
$email = preg_replace("/^https?:\/\/.*\?.*email=([^&]+).*$/", "$1", $url);
// xyz2#test.com
Use $_GET['email'] for parameters in URL.
Use $_POST['email'] for posted data to script.
Or use _$REQUEST for both.
Also, as mentioned, you can use parse_url() function that returns all parts of URL. Use a part called 'query' - there you can find your email parameter. More info: http://php.net/manual/en/function.parse-url.php
You can use the below code to get the email address after ? in the URL:
<?php
if (isset($_GET['email'])) {
echo $_GET['email'];
}
I a created function from Ruel's answer.
You can use this:
function get_valueFromStringUrl($url , $parameter_name)
{
$parts = parse_url($url);
if(isset($parts['query']))
{
parse_str($parts['query'], $query);
if(isset($query[$parameter_name]))
{
return $query[$parameter_name];
}
else
{
return null;
}
}
else
{
return null;
}
}
Example:
$url = "https://example.com/test/the-page-here/1234?someurl=key&email=xyz5#test.com";
echo get_valueFromStringUrl($url , "email");
Thanks to #Ruel.
$web_url = 'http://www.writephponline.com?name=shubham&email=singh#gmail.com';
$query = parse_url($web_url, PHP_URL_QUERY);
parse_str($query, $queryArray);
echo "Name: " . $queryArray['name']; // Result: shubham
echo "EMail: " . $queryArray['email']; // Result:singh#gmail.com
A much more secure answer that I'm surprised is not mentioned here yet:
filter_input
So in the case of the question you can use this to get an email value from the URL get parameters:
$email = filter_input( INPUT_GET, 'email', FILTER_SANITIZE_EMAIL );
For other types of variables, you would want to choose a different/appropriate filter such as FILTER_SANITIZE_STRING.
I suppose this answer does more than exactly what the question asks for - getting the raw data from the URL parameter. But this is a one-line shortcut that is the same result as this:
$email = $_GET['email'];
$email = filter_var( $email, FILTER_SANITIZE_EMAIL );
Might as well get into the habit of grabbing variables this way.
$uri = $_SERVER["REQUEST_URI"];
$uriArray = explode('/', $uri);
$page_url = $uriArray[1];
$page_url2 = $uriArray[2];
echo $page_url; <- See the value
This is working great for me using PHP.
In Laravel, I'm using:
private function getValueFromString(string $string, string $key)
{
parse_str(parse_url($string, PHP_URL_QUERY), $result);
return isset($result[$key]) ? $result[$key] : null;
}
A dynamic function which parses string URL and gets the value of the query parameter passed in the URL:
function getParamFromUrl($url, $paramName){
parse_str(parse_url($url, PHP_URL_QUERY), $op); // Fetch query parameters from a string and convert to an associative array
return array_key_exists($paramName, $op) ? $op[$paramName] : "Not Found"; // Check if the key exists in this array
}
Call the function to get a result:
echo getParamFromUrl('https://google.co.in?name=james&surname=bond', 'surname'); // "bond" will be output here

Send a javascript var to php [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 4 years ago.
I try to assign a string type javascript variable to a php variable and retrieve a table from database, I wrote all the code in a file.
I read date from input:
<input type="date" id="myDate" >
and by a listener I run myDate function, it produce sql1 that is a string, it should pass sql1 to $sql, I tried that users explain in other Q's but I don't get the right answer :
<script>
var dateBut = document.getElementById("myDate")
function myDate() {
var x = document.getElementById("myDate").value;
document.getElementById("demo3").innerHTML = x;
// sql1 string
var sql1 = "SELECT * FROM TSE(" + document.getElementById("demo3").innerHTML +")";
document.getElementById("demo2").innerHTML = sql1;
var tbl = document.getElementById("demo");
tbl.innerHTML = "";
var ch = document.getElementById("checkerWork");
<?php
// sql1 should pass to $sql;
$sql = ?>"SELECT * FROM TSE(" + document.getElementById("demo3").innerHTML + ")"<?php
mysqli_set_charset($conn, "utf8");
$result = $conn->query($sql);
?>
}
dateBut.addEventListener("change", myDate, false );
all of the code is in a php file.
thanks
I would send the contents of the variable to a PHP page via Ajax with jquery, then I would assign the data sent via get or post to the PHP variable, execute the query and return the result to the myDate () function. I'm not a native English speaker so if the answer is not clear tell me and I'll give you an example.

Get variable value by name from a String

This is for server side, regardless of client.
$data= file_get_contents('textfile.txt');
The textfile.txt contains
var obTemperature = "55";
var obIconCode = "01";
What can I enter so I can get echo obTemperature value of 55?
is there not a simple php interface to read var values by name?
please no over complicated /half answers /trolling,
You would be better off explaining what you want to do in general, but if you are tied to this file format and the format is consistent:
$data = str_replace('var ', '$', $data);
eval($data);
echo $obTemperature;
echo $obIconCode;
However, any other types of JavaScript code will cause a parse error.
Also, you can treat it as an ini file:
$data = str_replace('var ', '', parse_ini_string($data));
echo $data['obTemperature'];
Or just:
$data = parse_ini_string($data);
echo $data['var obTemperature'];
You can use a regular expression:
preg_match('/var obTemperature = "(\d+)";/', $data, $match);
$temperature = $match[1];
DEMO

How can I pass a PHP string into a Javascript function call?

I simple want to wan to pass php string into java script function here is the code. I know there is problem in sending string to javascript function but how can i solve it????If i pass integer value then it works fine it shows problem
in passing string
echo "<td><a id='".$row['Patient_Id']."' onclick=changename(".$row['Patient_Id'].",".$row['age'].",".$row['Notes'].") >".$row["Patient_Name"]."</a></td></tr>";
Here is the java script funtion
function changename(vlue,age,id)
{
alert(id);
var MyDiv1 = document.getElementById(vlue);
document.getElementById('age').innerHTML=age;
var MyDiv2 = document.getElementById('pname');
MyDiv2.innerHTML = MyDiv1.innerHTML; //d
var MyDiv3 = document.getElementById('hidden');
MyDiv3.value =vlue;
}
Your parameters are string values, so they should be enclosed in quotes:
echo "<td><a id='".$row['Patient_Id']."' onclick=changename( '".$row['Patient_Id']."' , '".$row['age']."' , '".$row['Notes']."' ) >".$row["Patient_Name"]."</a></td></tr>";
// ^----------------------^ etc
As it stands, JavaScript perceives your strings as identifiers. If you had checked your console you'd have seen corresponding errors (assuming these identifiers aren't defined).
your onclick doesn't have quotations
echo "<td><a id='".$row['Patient_Id']."' onclick='changename(".$row['Patient_Id'].",".$row['age'].",".$row['Notes'].")' >".$row["Patient_Name"]."</a></td></tr>";
^ //here ^ // and here

Categories