I want to pass php value in javascript. I run a query and apply if statement and while array on javascript. But always show empty result. I can't find the problem. anyone please help me. Thanks
<?php
session_start();
$SUserName=$_SESSION['view'];
include 'dbconnect.php';
$query="select * from user_permission where username='$SUserName'";
$result=mysql_query($query) or die (mysql_error());
?>
<script type="text/javascript">
d = new dTree('d');
d.add(0,-1,'Dhuronto');
<?php
if($SUserName=='sumon#dhuronto.com')
{
echo "d.add(1,0,'Admin','blank.php', 'Admin', 'main');";
}
else {
while ($row = mysql_fetch_array($result))
{
echo "d.add('$id','$pid','$node','$url', '$node', 'main');";
}
}
?>
</script>
Where are '$id','$pid','$node','$url', '$node' coming from?
while ($row = mysql_fetch_array($result))
{
echo "d.add('$id','$pid','$node','$url', '$node', 'main');";
}
Did you mean
while ($row = mysql_fetch_array($result))
{
echo "d.add('$row[id]','$row[pid]','$row[node]','$row[url]', '$row[node]', 'main');";
}
NB - i wouldn't use the above syntax myself, it being the only time you can write vars as $row[id]. I prefer
echo "d.add('" . $row['id']. "','" . $row['pid']. "'...
You are using the names of the columns as if they are variables. You need to get them from the array:
while ($row = mysql_fetch_array($result))
{
echo "d.add('{$row['id']}','{$row['pid']}','{$row['node']}','{$row['url']}', '{$row['node']}', 'main');";
}
Your code does not work because you have not defined values for $id, $pid, and so on. That said, you can use json_encode() to JavaScript encode PHP data types properly, assuming your text is UTF-8 encoded:
while ($row = mysql_fetch_array($result))
{
// I don't know your database schema, so this could be wrong
$args = array(
$row['id'], 0, htmlspecialchars($row['username']),
'blank.php', '', 'main'
);
// echo 'd.add.apply(d,' . json_encode($args) . ');';
echo 'd.add(' . implode(',', array_map('json_encode', $args)) . ');';
}
Note that dTree is sort of an outdated JavaScript library that has fallen behind current best practices. It was last updated in 2003! You might want to look into newer, better alternatives such as those mentioned at https://stackoverflow.com/questions/1710114/jquery-tree-plugin.
Related
Hi guys I am relatively new to php and am wondering how there is a cleaner way to retrieve data from my database and show it across different parts of the webpage?
For example see my current code...
<?php
$result = mysqli_query($mysqli,"SELECT * FROM members WHERE email='".$_SESSION['email']."'");
while($row = mysqli_fetch_array($result)){
if($_SESSION['email'] == $row['email']) {
// If you find the right user with the same E-Mail address, DO SOME COOL THINGS :)
}
echo '<h2>'. $row['username'] . '</h2>' ;
echo 'Hi, I am a ' . $row['yourage'] . ' year old ' . $row['orientation'] . ' ' . $row['gender'] . ' looking for a ' . $row['lookingfor'] . '.<br /><br />';
echo 'I am currently living in the ' . $row['location'] . ' area.';
echo '<button>Get in touch</button>' . '<br>';
echo '<br /><br />';
echo '<hr />';
echo '<h2>About me:</h2>';
echo $row['aboutme'] . '<br>';
}
mysqli_close($mysqli);
?>
If I copy this again on the page it kills the script but wondering what the best practice is?
First of all, a much better approach to this would be to separate your database and view code, for example by using an MVC framework (such as CakePHP).
But here is what I would do if was doing this a similar way to you: (You are only selecting one result from the database, if you were selecting many, this would be different.)
At top of page:
<?php
$email = $_SESSION['email'];
$result = mysqli_query($mysqli,"SELECT * FROM members WHERE email='".$email."'");
while($row = mysqli_fetch_array($result)){
$member = $row;
}
mysqli_close($mysqli);
?>
then whenever you need to display the data in the page: (for example)
My username is <?php echo $member['username']; ?>
Maybe you should separate the query script (below) from the viewing part.
query.php
<?php
$result = mysqli_query($mysqli,"SELECT * FROM members WHERE email='".$_SESSION['email']."'");
while($row = mysqli_fetch_array($result)){
if($_SESSION['email'] == $row['email']) {
// If you find the right user with the same E-Mail address, DO SOME COOL THINGS :)
}
$returnArray[] = $row['username'];
$returnArray[] = $row['yourage'];
//and so on;
}
mysqli_close($mysqli);
?>
Some view.php (or index.html renamed to index.php):
<?php
include('query.php');
var_dump($returnArray);
//Or with a foreach or however
But you should learn about MVC Model View Controller and as others said, use OO programming
Learn ajax- this will help you separate this code from your application. Just make the ajax call to this php and get the result and show them how you want to show.
For example-
In a your application, say app.html, at the point you want to fetch something from db-
$.ajax({
type: "GET",
url: "fetch.php", // your aove php file
function(response){
console.log(response); // you'll get all the rows here
response=JSON.parse(response);
for(var i=0; i<response.length; i++){
console.log(response[i].username); // show results in view
....
}
}
});
fetch.php
$myrows = array();
while($row = mysqli_fetch_array($result)){
array_push($myrows, $row);
}
echo json_encode($myrows);
The reality is you want a templating engine of some sort to filter your database results directly into the template.
So rather than dealing with echo commands to design a page, you want a raw template and then to inject data into that template from your database array.
You can use something standardized like Mustache or roll your own fairly easily (although rudimentary):
$output = '';
$tpl = fopen('template.html','r');
$tpl = fread($tpl, 100000);
$templateVars = array();
while($row = mysqli_fetch_array($result)){
$temporaryRow = $tpl;
foreach ($row as $k=>$v) {
$temporaryRow = preg_replace("/{{$k}}/i",$v,$temporaryRow);
}
$output .= $temporaryRow;
}
echo $output;
And then your template.html could be something like
<div>Hello, {{username}}</div>
I'm making simple basketball stats plugin to wordpress, and I'm using dropdown list a lot. I wanted to make function but I don't know how to pass arguments to MySQL. Here's my code:
function dropDown($tab, $option, $text){
$result = mysqli_query($con,'SELECT * FROM tab');
while($row = mysqli_fetch_array($result)){
echo "<option value=\"";
echo $row['option'] . "\">" . $row['text'];
echo "</option><br>";
}
}
and I would like to use it like this:
dropDown("team", "team_id", "name");
I tried with different quotation marks, dots etc but it doesn't seem to work.
#edit
I know PHP syntax (some of it) and I know how to use it, but I don't know how to pass $variables to MySQL query, and that's my main problem.
try
function dropDown($team, $team_id, $name) {
// use both three var where you want
$result = mysqli_query($con,'SELECT * FROM team');
echo "<select>";
while($row = mysqli_fetch($result)){
echo "<option value=\"";
echo $row['team_id'] . "\">" . $row['name'];
echo "</option>";
}
echo "</select>";
}
dropDown("team", "team_id", "name");
I have a table
Now.i have a function in my JS
function add()
{
<?php
include('conn.php');
$rs = mysql_query("select * from position");
$row = mysql_fetch_array($rs);
$ss=$row['Name'];
$sss=$row['nowb'];
$ssss=$row['totalb'];
$sssss=$row['nowc'];
$ssssss=$row['totalc'];
echo "add2()";
?>}
function add2(){
AddAddress("<?php echo $ss;?>","<?php echo $sss;?>/<?php echo $ssss;?><br /><?php echo $sssss;?>/<?php echo $ssssss;?>");
}
How to get the every date from my table?
Something like this?
function add() {
<?php
include('conn.php');
$rs = mysql_query("select * from position");
while ( $row = mysql_fetch_array($rs) ) {
$ss=$row['Name'];
$sss=$row['nowb'];
$ssss=$row['totalb'];
$sssss=$row['nowc'];
$ssssss=$row['totalc'];
echo 'AddAddress("' . $ss . '","' . $sss . '/' . $ssss . '<br />' . $sssss . '/' . $ssssss . '");';
}
?>
}
Didn't text the echo 'AddAddress....' line so I hop eI got all the single and double quotes in the right place??
Performing POST requests using Ajax here is an example of sending data from js to php.
also stop naming your vars s,ss,sss,ssss you will have no idea what they mean when you read your code tomorrow..
and try not to use mysql_* functions they have been deprecated switch to mysqli or pdo
I got what would you like to do. In your PHP file:
function add(){
<?php
include('conn.php');
$rs = mysql_query("select * from position");
echo "var data = [] ; "
while($row = mysql_fetch_assoc($rs)){
echo "
data.push({
name: '{$row['Name']}',
nowb: '{$row['nowb']}',
totalb: '{$row['totalb']}',
nowc: '{$row['nowc']}',
totalc: '{$row['totalc']}'
}); \n\r " ;
}
?>
add2(data);
}
function add2(data){
for (var i in data){
var row = data[i] ;
AddAddress(row.name, row.nowb, row.totalb, row.nowc, row.totalc);
}
}
If I understand the question correctly you want to know how to loop through an array in php.
$row = mysql_fetch_array($rs);
foreach($row as $value){
//Do something
}
Read up on it in the docs
http://php.net/manual/en/control-structures.foreach.php
I'm sure I'm doing something wrong here but I can't figure it out. I have tried several ways but no luck.
This is my controller:
$result = mysql_query("SELECT name FROM spa_packages") or die(mysql_error());
$names=array();
while ($row = mysql_fetch_row($result)) $names[]=$row[0];
mysql_free_result($result);
foreach ($names as $asd => $lol) {}
$this->set('anything', $lol);
This is where I display it:
if(!empty($anything)) {
echo " '<option value=" . $anything . '">' . $anything . '</option>';
}
Further to my comment and in more of an answer. You are doing something wrong. There is absolutely no reason to use mysql_ functions at all (they are deprecated) and you shouldn't be using any direct db access in an MVC framework like CakePHP
Your code should be more along the lines of
In your Controllers/SpaPackagesController.php index action:
$spaPacakges = $this->SpaPackage->find('all');
$this->set('spaPackages', $spaPackages):
In your Views/SpaPackages/index.ctp
<?php foreach ($spaPackages as $package): ?>
<!-- some html -->
<?php endforeach;?>
You really need to run through some CakePHP beginner tutorials as your question shows a big misunderstanding in how the framework works
Looks like you are trying to do this:
$result = mysql_query("SELECT name FROM spa_packages") or die(mysql_error());
$names = array();
while ($row = mysql_fetch_assoc($result)) {
$names[] = $row["name"]
}
$this->set('anything', $names);
mysql_free_result($result);
And:
if(!empty($anything)) {
foreach($anything as $name){
echo " '<option value=" . $name . '">' . $name . '</option>';
}
}
I have a simple function to SELECT from MySQL:
function dbSelect($query) {
$db = db(); // refers to a database connect function
$result = mysqli_query($db, $query);
while ($row = mysqli_fetch_array($result)) {
echo $row['f_name'] . ' : ' . $row['s_name'] . '</br>';
}
}
as you can see it accepts the $query var which would be:
$query = "SELECT * FROM user"; // or whatever
What I would like to do is pass the line:
echo $row['f_name'] . ' : ' . $row['s_name'] . '</br>';
as an arg in the function call, eg:
function dbSelect($query, $display)
and the $display be something like (which I would echo out under the while statement):
$display = $row['f_name'] . " : " . $row['s_name'] . "</br>";
The above line will give an undefined variable error, I know why.
How would I go about passing the $display to the function or defining it correctly?
ps. I know there is not any error checking, I'm just trying to figure this out, will add that later. :-)
Thanks for any help
Try this, to maintain separation from program logic to program output:
// some configuration file you include
$db = db(); // refers to a database connect function
// some common functions file
function dbSelect($query)
{
global $db;
$result = mysqli_query($db, $query);
return $result;
}
// output script
$records = dbSelect('SELECT * FROM somewhere');
// loop until cannot fetch any more rows from the record set
while ($row = mysqli_fetch_array($records))
{
echo $row['f_name'] . ' : ' . $row['s_name'] . '</br>';
}
Personally I would pass a template name into the function and have the template stored somewhere as a snippet of html which has standard replacement vars
So you may have something like this (note this won't work out the box will need some fiddling but its the concept)
define TEMPLATE_NAME = "<tr><td>%COL1%</td><td>%COL2</td></tr>";
$colstospitout = array('COL1'=>'f_name','COL2'=>'s_name');
function dbSelect($query,$reportcols,$templatename) {
while ($row = mysqli_fetch_array($result))
{
$template = str_replace("%COL1%",$reportcols['COL1'],$templatename);
$template = str_replace("%COL2%",$reportcols['COL2'],$templatename);
echo $template;
}
}
dbSelect($inputquery,$colstospitout,TEMPLATE_NAME);
There are two ways to do it. The proper way to do it would be to have this function only run the query and return the results. You could make another function that outputs the results. This way you have a clear separation of logic in your code.
However, if you know that you want it done in this way, something like this should work:
function dbSelect($query, $format) {
$db = db();
$result = mysqli_query($db, $query);
while ($row = mysqli_fetch_array($result))
{
echo preg_replace_callback("/\{\{\s*(\w+)\s*\}\}/", function($matches) use ($row) { $column = trim($matches[1]); return isset($row[$column]) ? $row[$column] : $matches[0]; }, $format);
}
}
Where the arguments could look something like:
dbSelect("SELECT * FROM user", "{{ f_name }} {{ s_name }}");
You can't pass it the way that you're passing it because $row doesn't exist when you call the function (because it gets defined inside of the function). In addition, your variables in would be evaluated once when the function is called, not each time in the while loop.
And before anyone makes a "suggestion": eval is not an option.