I'm trying to display a PHP variable using javascript/jquery but it's displaying 'null'.
if(mysql_num_rows($checkBan) > 0){
$bannedDate = $checkBan['banLength'];
if(preg_match('/[0-9]/',$bannedDate)){
list($yyyy,$mm,$dd) = explode('-',$bannedDate);
$date = $mm."-".$dd."-".$yyyy;
}
//$date = "test"; when this is uncommented it appears in the alert so I know the json_encode is working fine
?>
<script type ="text/javascript">
var bannedUntil= <?php echo json_encode($date); ?>;
alert('Your account has been banned until ' + bannedUntil +'. Please contant an administrator if you believe this is an error');
</script>
<?
}
The alert appears just fine, but the bannedUntil variable is null. However, when the second date variable is uncommented it appears in the alert. It's not a separate function so I don't see why the scope would be an issue.
I am seeing you use $checkBan as a result resource in mysql_num_rows(), then attempt to access an array key from it without fetching. You appear to be missing a call to mysql_fetch_assoc():
if(mysql_num_rows($checkBan) > 0){
// Fetch a row from the result resource $checkBan
$row = mysql_fetch_assoc($checkBan);
$bannedDate = $row['banLength'];
// etc...
}
Another tip: It looks like you are getting a standard MySQL date format back as YYYY-MM-DD and converting it with string operations in PHP to MM-DD-YYYY. Just retrieve it in that format in your query to begin with and avoid the explode() and list() calls in your PHP application code.
SELECT DATE_FORMAT(banLength, '%m-%d-%Y') FROM yourtable
Related
I have a little problem in my code, please review it and help me.
I want to assign value of the span tag(fetched by id in html) to a php variable and then run a sql query to fetch record of the related value in the table. Here is my code.
I tried it in different ways but it not works.
I print the sql query and its absolutely right but does not show the correct result. I copied that printed sql query and paste it into phpmyadmin query section and run it there. Then it works fine and show related records. Please help
$regg = '<span id="modal-myvalue"></span>';
$fee_detail = "SELECT * FROM `fee_enroll` WHERE registeration = '$regg' AND mode = 'ENABLE'";
//here i print the query and its output is correct but doesn't show the correct record here.
echo $fee_detail;
$result_fee = mysqli_query($con, $fee_detail);
while($row_fee = mysqli_fetch_assoc($result_fee)) {
echo $row_fee['registeration'];
}
The data which i want to fetch in span tag(in id) is sent from a button through this script:
<script type="text/javascript">
var ATTRIBUTES = ['myvalue'];
$('[data-toggle="modal"]').on('click', function(e) {
var $target = $(e.target);
var modalSelector = $target.data('target');
ATTRIBUTES.forEach(function(attributeName) {
var $modalAttribute = $(modalSelector + ' #modal-' + attributeName);
var dataValue = $target.data(attributeName);
$modalAttribute.text(dataValue || '');
});
});
</script>
and the button code is
<a class="btn" type=submit data-toggle="modal" data-target="#model-view" data-myvalue="<?php echo $row['registeration']; ?>">VIEW Detail</a>
When i print the query it shows:
(SELECT * FROM `fee_enroll` WHERE registeration = 'FA12-BSE-094' AND mode = 'ENABLE')
which works correctly in phpmyadmin query section. but not works here when i want to execute.
You can try DOMDocument as follows,
$regg = '<span id="modal-myvalue">FA12-BSE-094</span>';
$doc = new DOMDocument();
$doc->loadHTML($regg);
$elements = $doc->getElementsByTagName('span')->item(0);
var_dump($elements->nodeValue);
And then you can use this variable in query like below,
$fee_detail = "SELECT * FROM `fee_enroll` WHERE registeration = '$elements->nodeValue' AND mode = 'ENABLE'";
You cannot insert a variable like that. See this answer.
Complex (curly) syntax
Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$.
Curly braces in string in PHP
My suggestion should be to change the query string into the following:
$fee_detail = "SELECT * FROMfee_enrollWHERE registeration = '{$regg}' AND mode = 'ENABLE'";
Please help me ...
I'm a newbie! Please tell me what to do.
processed.php
<?php
include_once('../../dbConnect.inc.php');
$sql="SELECT name FROM artist";
$artist = select($sql);
disconnect();
$output_items = array();
while($row = mysql_fetch_array($artist))
{
$results[] = array('label' => $row['name']);
}
echo json_encode($results);
?>
index.php
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/smoothness/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#artist").autocomplete(
{
source: 'processed.php',
});
});
</script>
I have this problem: http://jsbin.com/alaci5
Autocomplete expects the source (when an URL is specified to filter out the results).
From documentation:
String: When a string is used, the Autocomplete plugin expects that
string to point to a URL resource that will return JSON data. It can
be on the same host or on a different one (must provide JSONP). The
Autocomplete plugin does not filter the results, instead a query
string is added with a term field, which the server-side script should
use for filtering the results. For example, if the source option is
set to "http://example.com" and the user types foo, a GET request
would be made to http://example.com?term=foo. The data itself can be
in the same format as the local data described above.
So in your PHP code you have to do:
include_once('../../dbConnect.inc.php');
$sql="SELECT name FROM artist WHERE `name` like '%".mysql_real_escape_string($_GET['term'])."%'";
$artist = select($sql);
$output_items = array();
while($row = mysql_fetch_array($artist)) {
$results[] = array('label' => $row['name']);
}
echo json_encode($results);
That autocomplete function is probably passing a few variables to your processed.php page.
Use var_dump($_GET) to see all the things you're being passed.
Inside one of those $_GET elements, you'll have the contents of the text box as they exist on the page. For the sake of demonstration, I'm going to use $_GET['text']. You'll need to find out which part holds the data you need.
What you'll need to do is search the database using this value for a list of results to return.
$sql="SELECT name FROM artist";
$artist = select($sql);
This is your script as it exists. What it may end up looking similar to is this.
$text_input = mysql_escape_string($_GET['text']);
$sql="SELECT name FROM artists WHERE name LIKE '%$text_input%'";
$artist = select($sql);
You'll want to get results that are similar to the inputted text on the user-facing page.
A few notes for you
I used mysql_escape_string() solely to may what you already have. While this does work (driving around a busted-ass chevy pacer works too, but there are much better ways though), its not recommended, which sets us up for point 2.
Using the old mysql extension is not really a good idea, its been replaced by mysqli, and PDO.
you'll need to escape your data, this is how its done with mysqli.
I have followed his popular tutorial to connect Android to MySQL:
http://www.helloandroid.com/tutorials/connecting-mysql-database
It is great at encoding the data back in JSON and displaying rows of data.
My question: What id I want to return just a single value, a single varaible from PHP to Java?
Here is my PHP:
$sql="SELECT AVG(rating) FROM ratings WHERE item_id = 1";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
echo $row[0];
I want to send that last "echo" back to Android, on the guidelines of that tutorial above, how would I do this?
$row is an array and it should have a value like:
$row['AVG(rating)'] = <some value>
All you need to do is throw the json_encode function around row and echo it out
print(json_encode($row));
This should get you the single value json encoded string that the java code can read.
If you are using WebView try addJavascriptInterface(new JavaScriptInterface(this), "Android") http://developer.android.com/guide/webapps/webview.html and call
<script type="text/javascript">
function showAndroidToast(avg_value) {
Android.echo(avg_value);
}
</script>
I've a problem when print the content session, because when create the session, the variable is string (varchar obtained from a mysql field):
Initial variable: 09680040
Print with alert or display in div: 9680040
???
PHP CODE
$query = "SELECT nombre, apellidop, apellidom, tUser FROM users WHERE ncontrol = '$numeroControl'";
$result = mysql_query($query) or die (mysql_error());
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
$_SESSION['n_control'] = $user['ncontrol'];
}
JS CODE
........
alert <?php echo $_SESSION['n_control'];?>;
JQuery CODE
('#div').html(<?php echo $_SESSION['n_control']; ?>);
EDIT: The problem is only when display alert, and when put content on div in jquery
('#div').html(<?php echo $_SESSION['n_control']; ?>);
This produces the following line which is sent to your browser:
('#div').html(09680040);
This will be interpreted as an integer by your Javascript parser. Simply put quotes around it in order to make it a string:
('#div').html('<?php echo $_SESSION['n_control']; ?>');
This is a javascript question. It has nothing to do with the $_SESSION or mysql_query part.
In essence your final JS code will become:
alert 09680040;
Ignoring the obvious syntax error, Javascript will see that as numeric constant.
You'll have to create a Javascript string in your PHP code to keep all contents. Use json_encode.
alert(<?php echo json_encode($_SESSION['n_control']);?>);
(Either way your description of the problem is incorrect, and the example code certainly isn't your actual code. So this is my guessing answer..)
Try:
$_SESSION['n_control'] = strval($user['ncontrol']);
In my one of php file I am running one query whatever query result is display that value I want to put in the number.js file. even I copied .js code in that PHP file but in the main file(index.php) I am facing conflict of the js file . Thats why I cant copied js file into that php file . Please provide me the soution. below that I am copied my code of PHP as well as js file.
In PHP code
$query_string = "SELECT COUNT(Email) AS total FROM Contact INNER JOIN CompanyBranch ON Contact.CompanyBranchID = CompanyBranch.CompanyBranchID INNER JOIN Company ON Company.CompanyID = CompanyBranch.CompanyID INNER JOIN CompanyIndustry ON Company.CompanyID = CompanyIndustry.CompanyID INNER JOIN IndustrySubindustry ON CompanyIndustry.IndustrySubindustryID = IndustrySubindustry.IndustrySubindustryID WHERE CompanyBranch.GlobalRegionID = '$global_region' AND IndustrySubindustry.IndustryID = '$industry' AND IndustrySubindustry.SubindustryID = '$sub_industry'";
$query_string = strtolower($query_string);
$result_data = mysql_query($query_string) or die();
//$tmp = mysql_fetch_array($result_data);
$row = mysql_fetch_assoc($result_data);
$total_lead = $row['total'];
echo json_encode($total_lead);
whatever value get in the $total_lead variable that I want to redirect into the number.js file
Code in the number.js file
var leads=0;
I want the var_leads=$total_lead (the value come from the php file).
How it is possible?
.js files will be default NOT be executed as PHP scripts on a server, unless you tell the webserver to do so. That means you cannot embed PHP code into a .js file and have it fill things in for you.
Unless you do want to modify your server to force PHP handling of .js files, you'd be better off doing something like this:
yourfile.php:
<?php
... do query stuff here ...
?>
<html>
<head>
<script type="text/javascript">var leads = <?php echo json_encode($total_leader) ?>;</script>
<script type="text/javascript" src="number.js"></script>
</head>
That'll set the leads variable for you with the query results, then load the rest of the number.js script which then (supposedly) uses that variable.
The alternative is having a piece of JS code that performs an AJAX call back to your server to fetch the number dynamically at page load time.
You can look here for appropriate PHP-JSON libraries to do this job:
http://www.php.net/releases/5_2_0.php
http://pecl.php.net/package/json
JSON page: http://www.json.org/
I don't know the full context of your application, but if you are making an AJAX request to this script, you need to use a callback or onreadystate change, depending on wether the call is asynchronous.
If this script also loads a page, then you need to echo out the value in the context of actual tags.
You could also run your PHP inline with the JavaScript. Take a look at this quick example for instance:
<?php
$query_string = "Your select statement...";
$query_string = strtolower($query_string);
$result_data = mysql_query($query_string) or die();
//$tmp = mysql_fetch_array($result_data);
$row = mysql_fetch_assoc($result_data);
$total_lead = $row['total'];
?>
<script type="text/javascript">
var leads = <?=$total_leads?>; //as integer
var leads = '<?=$total_leads?>'; //as string
//other js stuff
</script>
You can use this:
var obj = <?php echo json_encode(your_json_object) ?>
var jsonObject = JSON.parse(obj)