In database table I have age column in which have more than 50 rows.
id age
1 45
2 41
3 09
......
60 11
I always have 10 keys in array ,
<?php
$arr = array(0,0,0,0,0,0,0,0,0);
echo json_encode($arr)."<br>";
$con = mysqli_connect('127.0.0.1','app_user2','qwe123','test');
$select="select age from ad;";
$res = mysqli_query($con, $select);
while ($row=$res->fetch_assoc()) {
$arr=array_slice($arr,1,9);
//$arr[]=$row['id'];
$arr[]=array($i++, (int)$row['age']);
echo json_encode($arr)."<br>";
}
?>
I'm getting following output=>
[0,0,0,0,0,0,0,0,0,[0,45]]
[0,0,0,0,0,0,0,0,[0,45],[1,41]]
[0,0,0,0,0,0,0,[0,45],[1,41],[2,11]]
[0,0,0,0,0,0,[0,45],[1,41],[2,11],[3,21]]
[0,0,0,0,0,[0,45],[1,41],[2,11],[3,21],[4,44]]
.............................
[[1,41],[2,11],[3,21],[4,44],[5,13],[6,15],[7,12],[8,7],[9,14],[10,11]]
........................
Now when i execute
echo json_encode($arr)
in JavaScript i'm getting only last 10 values. i want to execute all the rows one by one. how can i do that? Is it possible?please help.
here is my script code
<script type="text/javascript">
var data=[];
data=<?php echo json_encode($arr); ?>;
document.write(data);
</script>
That's because your string isn't in a valid json format. Then you get output of just one line. You may consider build in a correct way like:
$myArray = []
while ($row=$res->fetch_assoc()) {
$arr=array_slice($arr,1,9);
//$arr[]=$row['id'];
$arr[]=array($i++, (int)$row['age']);
array_push($myArray, $arr);
}
then:
data=<?php echo json_encode($myArray ); ?>;
(PS.: hardcode server side code in javascript isn't a good practice)
On each run through the loop, you assign $arr using array_slice and assign 9 elements to it (starting from element 1, length 9). Later in the loop iteration, you add a new element to the end of the array with a $arr[] = ... assignment.
Since you are assigning the array to have 9 elements and then adding 1 element on each iteration, it will always end up being 10 elements long at most, and no more.
Related
I used to use this kind of code before like 1 year ago and it worked.
Now I got a problem with the php code when I fill my array with elements from the database I can't do the autocomplete, but when I comment the part where I get the code form the database and uncomment //$elements = array("25qt", "45tr", "az12"); than the autocomplete works.
It looks like the array is filled correctly from the database cause when I open the php file alone and do a var_dump($elements); i get the content of the array accordingly. Any idea why its not working when i fill the array from the db but it works if I use an array like $elements = array("25qt", "45tr", "az12");.
HTML code:
<input id="tegjithepjeset" type="text" class="form-control">
jQuery code:
<script type="text/javascript">
$(document).ready(function(){
$("#tegjithepjeset").autocomplete({
source:'allParts.php',
minLength:1
});
});
</script>
Php code:
<?php
// An empty array:
$data = array();
// Create connection
include 'dbinfo.php';
$con=#mysqli_connect("$host","$user","$password","$db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$queryString = "SELECT code FROM ".$table;
$query =mysqli_query($con,$queryString);
$elements = array();
while($rowDB=mysqli_fetch_array($query)){
$elements[]="".$rowDB[0];
}
//var_dump($elements);
//$elements = array("25qt", "45tr", "az12");
//Loop through the array to find matches:
foreach ($elements as $elm) {
// Add matches to the $data array:
if (stripos($elm, $_GET['term']) !== false) $data[] = $elm;//here we fill our empty array with values
} // End of FOREACH.
// Return the data:
echo json_encode($data);
?>
Replace the $elements array code as shown below.
$elements = array();
while($rowDB=mysqli_fetch_array($query)){
// $elements[]="".$rowDB[0];
$elements[]=$rowDB[0];
}
my DB as follows,
date income expenses maincat
2015-02-06 10000 salary
2015-02-05 500 bank charges
2015-02-05 300 rent
2015-02-01 500 bonus
and i'm using following sql query to get DB values.
$sql= mysqli_query($con,"SELECT maincat as label,income as value FROM transaction where date BETWEEN '$date1' AND '$date2' AND email='$user' GROUP BY maincat") or die ("error3");
and it goes though following php query,
$arr = array();
While($row1 = mysqli_fetch_assoc($sql)){
$arr[] = $row1;
}
$ar = array_values($arr);
and it gives out put like this,
[{"label":"income","value":"10000"},{"label":"bank charges","value":""},{"label":"rent","value":""},{"label":"bonus","value":"500"}]
and I'm passing that values to java script(Morris.js) to show it in the donut chart. but it doesn't work. when there values as,
[{"label":"income","value":"10000"},{"label":"bonus","value":"500"}]
it works fine.i cant put "" values as "0" because there is no actual income as "bank charges" or "rent" (they are expenses) is there any method to remove this empty values ({"label":"bank charges","value":""} ) from above and get out put as,
[{"label":"income","value":"10000"},{"label":"bonus","value":"500"}]
and my morris.js code as follows,
<script>
Morris.Donut({
element: 'donut',
resize : true,
data : <?php echo json_encode($ar); ?>,
backgroundColor: '#0011',
labelColor: 'black',
colors:[
'#A4A4A4','#FE2E64','#0B610B','#0B615E',
'#FF8000','#088A68','#4B8A08','#A9D0F5',
'#5F4C0B','#F3F781','#81BEF7','#04B431',
'#D7DF01','#BE85F7','#BE59F7','#BE81F7',
'#F4FA58','#0431B4','#D8D8D8','#4C0B5F',
'#086A87','#F7D358','#DF7401','#B18904',
'#045FB4',
],
});
</script>
thank you..
Why not just use a loop to filter the empty items?
$legalArray = array();
foreach($ar as $item){
if(is_numeric($item['value']))
$legalArray[] = $item;
}
Output the $legalArray.
You should check you sql code
SELECT maincat as label,income as value FROM transaction where date BETWEEN '$date1' AND '$date2' AND email='$user' AND label != '' AND value != '' GROUP BY maincat"
May have my query wrong think there is a better way of putting that,
also you can use php to do the check
While($row1 = mysqli_fetch_assoc($sql)){
if (!empty($row1['label']) && !empty($row1['value']))
$arr[] = $row1;
}
I am working on a project where I have divisions stored in mysql database with the "division id" and the "division name";
what I want to have is so that i use php to do a "while" loop and go through all the divisions;
then for each division it creates a button which will trigger a javascript function…
I have done a lot of testing on this so I know certain parts are working…; here is my code:
<p id="id57512">How are you?</p>
<script>
var g_myobj = {};
</script>
<?php
$result_g1 = mysql_query("SELECT * FROM divisions");
while($row = mysql_fetch_array($result_g1, MYSQL_BOTH))
{
$div_id=$row[div_id];
$div_name=$row[div_name];
$button_id="b";
$button_id.=$div_id;
$function_id="f";
$function_id.=$div_id;
?>
<button id=<?php echo $button_id; ?>><?php echo $div_name; ?></button>
<script>
var f_id='<?php echo $function_id; ?>';
var b_id='<?php echo $button_id; ?>';
var div_id='<?php echo $div_id; ?>';
var newFieldName = f_id;
var newFieldValue = function() {document.getElementById("id57512").firstChild.nodeValue=gman_code1(div_id);};
g_myobj[newFieldName] = newFieldValue;
var gman_code1 = function(number) {
var result1 = number*2;
console.log(result1);
return result1;//add return statement
}
//define the behavior
document.getElementById(b_id).addEventListener("click", g_myobj[f_id] , false);
</script>
<?php
}
the function names need to be a variable; but I figured out how to do that by making it an object; and so can access the different functions that way…
I basically tested this all when it was not in a loop; where I manually had it do everything twice (even creating the functions in the object) and it all worked fine…
basically when you click on a button it is supposed to send a number to that "p" container and multiply it by 2
when I did it manually and not in loop i just had it create the object g_myobj first and then just started adding items to the object…
but now that i am doing this in a loop - I felt I could not have the statement that creates the empty object in the loop or it would just keep recreating it; so I went above the loop and had the object created there in its own "script" tags all by itself…
that part may be a problem with this, not sure at all…
another potential problem is that I am not sure if I can do all this in a loop like this
it is a "php loop" and so maybe this just all cannot be done in a loop like that…
What is going on is the first button works but none of the others do…
So, I am hoping someone can advise me on what I am doing wrong on this…
Thanks so much...
If all you are trying to do is send a number to <p> and multiply it by 2, see this one liner function. I assume you are trying to accomplish more than just the multiplying thing otherwise you probably would have just done a simple function like below...
Also, I'm sure you will get lots of comments on it, but you should not be using the mysql_ functions anymore. They are both deprecated and potentially unsafe. You should use mysqli or PDO prepared statements.
On your button, you should probably put quotes around the id="yadayada" instead of id=yadayada. jQuery may be a good option for your js to handle functions or what-have-you.
<p id="id57512">How are you?</p>
<?php
$result_g1 = mysql_query("SELECT * FROM divisions");
while($row = mysql_fetch_array($result_g1, MYSQL_BOTH)) {
$div_id = $row[div_id];
$div_name = $row[div_name];
$button_id = "b$div_id";
$function_id = "f$div_id"; ?>
<button id="<?php echo $button_id; ?>" onClick="MyRadFunction('<?php echo $div_id; ?>')">
<?php echo $div_name; ?></button>
<?php } ?>
<script>
function MyRadFunction(DivId) {
$("#id57512").html(DivId*2);
// var NewNum = $("#id57512").text();
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
When rendering your button, you should wrap the id in quotes, e.g.
<button id='<?php echo $button_id; ?>'><?php echo $div_name; ?></button>
Here I am getting values from textarea in array variable.
After that I convert javascript variable to PHP variable and perform some processing over it.
After process completed again I convert PHP to JS and alert. But when I alert, it gives empty result.
<script>
$( "#convert" ).click(function() {
var arabic = document.getElementById("ar").value; // ar is id of text area
<?php $ar_terms = "<script>document.write(arabic)</script>"?>
<?php
$string=implode(",",$ar_terms);
$result = array();
foreach ($ar_terms as $term) {
// echo $Arabic->ar2en($term);
array_push($result, $Arabic->ar2en($term));
}
$result=implode(",",$result);
?>
var arabic = new Array();
arabic='<?php echo $result; ?>';
alert(arabic);
});
</script>
Entire code is here : https://gist.github.com/karimkhanp/d4ac41fa864fd8ae0521
You can do one thing in this scenario to pass the variable from PHP to js. You can convert the array using json_encode() before echoing:
$result=json_encode( implode(",",$result) );
As a result, when you assign this variable to js in the <?= ?> block, it will read the json string and thus the array will be assigned:
arabic='<?php echo $result; ?>';
I'm trying to make a very simple autocomplete function on a private website using a trie in JavaScript. Problem is the examples I have seen and trying are just using a predefined list in a JavaScript array.
e.g. var arrayObjects = ["Dog","Cat","House","Mouse"];
What I want to do is retrieve MySQL results using PHP and put them into a JavaScript array.
This is what I have so far for the PHP (the JavaScript is fine just need to populate the array):
<?php
$mysqli = new mysqli('SERVER', 'U/NAME', 'P/WORD', 'DB');
if (!$mysqli)
{
die('Could not connect: ' . mysqli_error($mysqli));
}
if ($stmt = $mysqli->prepare("SELECT category.name FROM category")) {
$stmt->bind_result($name);
$OK = $stmt->execute();
}
while($stmt->fetch())
{
printf("%s, ", $name);
}
?>
Then I want to insert essentially each value using something like mysql_fetch_array ($name); (I know this is incorrect but just to show you guys what's going on in my head)
<script> -- this is the javascript part
(function() {
<?php while $stmt=mysql_fetch_array($name))
{
?>
var arrayObjects = [<?php stmt($name) ?>];
<?php }
?>
I can retrieve the results echoing out fine, I can manipulate the trie fine without MYSQL results, I just can't put them together.
In this case, what you're doing is looping through your result array, and each time you're printing out the line var arrayObjects = [<?php stmt($name) ?>];. However this doesn't convert between the PHP array you're getting as a result, and a javascript array.
Since you started doing it this way, you can do:
<?php
//bind to $name
if ($stmt = $mysqli->prepare("SELECT category.name FROM category")) {
$stmt->bind_result($name);
$OK = $stmt->execute();
}
//put all of the resulting names into a PHP array
$result_array = Array();
while($stmt->fetch()) {
$result_array[] = $name;
}
//convert the PHP array into JSON format, so it works with javascript
$json_array = json_encode($result_array);
?>
<script>
//now put it into the javascript
var arrayObjects = <?php echo $json_array; ?>
</script>
Use json_encode to turn your PHP array into a valid javascript object. For example, if you've got the results from your database in a php array called $array:
var obj = "<?php echo json_encode($array); ?>";
You can now use obj in your javascript code
For the auto-completion you can use the <datalist> tag. This is a relatively new feature in HTML5 (see support table) but the polyfill exists.
Fill the <option> tags in php when building the page and you a are done.