I seem to be having an issue with array_fill().
I have a MYSQL table that has
------------------------
id - username - tickets
01 BOB 14
02 JIM 22
03 KYLE 9
-----------------------
I'm trying to save the values to an array, and
for each ticket the user has, the username is added to the array...
$select=$conn->query("SELECT * FROM table") or die (MySQL_error());
while($r = $select->fetch()){
$tickets_array = array_fill(0, $r['tickets'], $r['username']);
}
After this I am trying to push the values in $tickets_array to a javascript
array.
var tickets = new Array();
<?php foreach($tickets_array as $key => $val){ ?>
tickets.push('<?php echo $val; ?>');
<?php } ?>
The code is working. However, I am only getting the first result from the database. tickets = 'BOB','BOB','BOB','BOB','BOB','BOB','BOB','BOB','BOB','BOB','BOB','BOB','BOB','BOB'
the other results are not being pushed to the javascript array for some reason.
Any ideas of what I am doing wrong, and how I can fix it?
Thanks in advance.
Not sure why you are using array_fill, I would use fetch_all()
http://php.net/manual/en/mysqli-result.fetch-all.php
$select=$conn->query("SELECT * FROM table") or die (MySQL_error());
$tickets_array = $select->fetch_all());
I would try this approach. Much simpler and it populates your array the way you want.
$tickets = array();
while($r = $select->fetch_object()) {
for($i = 1; $i <= $r->tickets; $i++) {
$tickets[] = $r->username;
}
}
Related
I have Decimal data type in my database with value 0.00 but in JSON result is .00, How I can convert so i can still get 0.00 in result ?
I working in Jquery.. Thanks
This my code
<?php
include "../../../config/config.php";
$kd_entitas=$_POST['kd_entitas'];
$tglAwal = $_POST['tglAwal'];
$tglAkhir = $_POST['tglAkhir'];
$con = sqlsrv_connect(serverNameAST,$connectionInfoAST) or die('Unable to Connect');
if( $con === false )
{
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
else{
//$sql = "SELECT SELECT #rownum := #rownum + 1 AS urutan, t.* FROM SYS_DEPT t, (SELECT #rownum := 0) r";
$sql="[Daily_report_r] '$kd_entitas','$kd_entitas','$tglAwal','$tglAkhir'";
$result = sqlsrv_query($con, $sql, array(), array( "Scrollable" => 'static' ));
$data = array();
while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))
{
$data[] = $row;
}
$datax = array('data' => $data);
echo json_encode($datax);
}
?>
Result JSON in field oustand
Result from my database sql server
You have two problems here:
When you're getting the data from database all values will be strings. If you want a specific number to be a double then you have to explicitly cast it to a double.
If you want to preserve zero fraction in json you have to use JSON_PRESERVE_ZERO_FRACTION flag in json_encode. See http://php.net/manual/en/function.json-encode.php for details.
But this solution will preserve only one zero and will only work on numbers of type double. If you want to have more zeros after coma you have to leave the number in the string and handle yourself.
If the number from the database is returned without the fraction part then check your field type or field precision.
I'm trying to insert into a string all emails retrieved from the database, so I can use javascript to check if the email typed by the user into a form field is already registered. I'm trying to use json_encode().
$conectar = mysqli_connect(HOST, USER, PASS, DATABASE);
$listarCorreos = " SELECT userEmail
FROM usuarios
";
$resultado = mysqli_query($conectar,$listarCorreos);
$arrayEmails = mysqli_fetch_array($resultado);
foreach($arrayEmails as $row){
$emails[]=array($row['userEmail']);
}
echo json_encode($emails);
Now, I'm getting this error:
Warning: Illegal string offset 'userEmail' in /home/verificarEmail.php
on line 21
Line 21 is $emails[]=array($row['userEmail']);
What Am I doing wrong?
UPDATE:
I'm also trying:
$resultado = mysqli_query($conectar,$listarCorreos);
$emails = array();
while($row = mysql_fetch_assoc($resultado)) {
$emails[] = $row;
}
echo json_encode($emails);
And I get this error:
Warning: mysql_fetch_assoc() expects parameter 1 to be resource,
object given in /home/verificarEmail.php on line 18
Line 18: while($row = mysql_fetch_assoc($resultado)) {
Use MYSQLI_ASSOC like below
$conectar = mysqli_connect(HOST, USER, PASS, DATABASE);
$listarCorreos = " SELECT userEmail
FROM usuarios
";
$resultado = mysqli_query($conectar,$listarCorreos);
while ( $row = mysqli_fetch_array($resultado, MYSQLI_ASSOC) ) {
$emails[]=array($row['userEmail']);
}
echo json_encode($emails);
There are a few problems there. To get your emails in an array do:
$resultado = mysqli_query($conectar,$listarCorreos);
if(!resultado) die($mysqli_error($conectar));//check for errors
$emails = mysqli_fetch_all($resultado);//fetch all results
echo json_encode($emails);
That should get your code working or show you the error. However, please don't do this.
so I can use javascript to check if the email typed by the user into a
form field is already registered
This is a terrible idea security wise because it will expose all your users' emails to people who are not even registered to your site. You should instead look up the desired username in the DB directly. If it's not there, then it hasn't been registered before. The Javascript side should only get a available or not available response.
The process (pseudo-code):
SELECT userEmail from usarios WHERE userEmail = ? ? is email to look for
execute query and capture $resultado
If $resultado is false, die(mysqli_error($conectar)) to show error
if mysqli_num_rows($resultado) === 0 email is available; else not available
Echo available or not available to Javascript
use the code like below
$conectar = mysqli_connect(HOST, USER, PASS, DATABASE);
$listarCorreos = " SELECT userEmail
FROM usuarios
";
$resultado = mysqli_query($conectar,$listarCorreos);
while ( $row = mysqli_fetch_array($resultado) ) {
$emails[]=$row['userEmail'];
}
echo json_encode($emails);
use the code like below
$conectar = mysqli_connect(HOST, USER, PASS, DATABASE);
$listarCorreos = " SELECT userEmail
FROM usuarios
";
$resultado = mysqli_query($conectar,$listarCorreos);
while ( $row = mysqli_fetch_array($resultado) ) {
$emails[]=$row['userEmail '];
}
echo json_encode($emails);
I am currently working on creating a Flot JavaScript Time Series Line Graph. The graph analyses the number of users who create an account with against the time that the account was created.
Here is a screenshot of the users table
I have so far been able to retrieve the created_date column in the users table x asis used for the graph. The y axis is then calculated using the COUNT() function in a separate query. My codes are found below.
PHP:
<?php
include "connection/connect2.php";
$datecreated = "SELECT created_date FROM users";
$rundatecreated = mysql_query($datecreated);
$foundnum = mysql_num_rows($rundatecreated);
while ($runrows = mysql_fetch_assoc($rundatecreated)) {
$dataset1[] = $runrows['created_date'];
}
if (is_array($dataset1)){
foreach($dataset1 as $x) {
$query = mysql_query("SELECT created_date, count(created_date) as date FROM users WHERE created_date='$x' ");
while ($runquery = mysql_fetch_assoc($query)){
$y[]= $runquery['created_date'] .",".$runquery['date']."<br>" ;
}
}
$graph=implode(" ", $y);
echo $graph;
} else {
echo "error";
}
?>
I then store the data retrieved using these two queries into an array, as shown below.
I am unsure of how to convert the date data currently retrieved using my PHP codes into JavaScript timestamp format. Is there any way I can do so using PHP codes?
1) You need only one SQL query to achieve this instead of one plus 1 per date. for this use grouping in the query.
2) To get timestamps from your dat values use the getTimestamp() method and multiply by 100 to convert from UNIX timestamps to JavaScript timestamps.
3) Flot need the data for a data series as array of array (data points). This can then be encoded as JSON and printed inside the JavaScript or fetched by AJAX.
Updated code (not tested but should be a good starting point):
<?php
include "connection/connect2.php";
$query = mysql_query("SELECT created_date, count(*) as date FROM users GROUP BY created_date ");
$foundnum = mysql_num_rows(mysql_query($query));
while ($runquery = mysql_fetch_assoc($query)){
$graph[] = array((new DateTime($runquery['created_date']))->getTimestamp() * 1000 , $runquery['date']);
}
if ($foundnum > 0) {
echo json_encode($graph);
} else {
echo "error";
}
?>
I would like to seek some help with my query problem in php...I want to do is count all (atic) with the same number and if the specific (atic) is equal to 7 my Insert query will execute to that (atic).
The problem is my count query wont work as i wanted....and execute my insert query to all aic even the count is not = 7.
current code:
<?php
mysql_connect("localhost","root","") or die("cant connect!");
mysql_select_db("klayton") or die("cant find database!");
$total = NULL;
$count = "SELECT count(t.atic) as '$total', t2.name FROM app_interview as t, tb_applicants as t2 WHERE t.atic = t2.aic GROUP BY t.atic";
$query = mysql_query($count) or die (mysql_error());
while($rows =mysql_fetch_array($query)){
if($query = 7){
mysql_query("INSERT INTO afnup_worksheet (faic,fnl_name,interview,fregion,ftown,funiq_id,fposition,fsalary_grade,fsalary,dateinputed) SELECT DISTINCT atic, atname,(SELECT sum(inttotal) FROM app_interview t2 WHERE t2.atic = t.atic)/7, region, town, uniq_id, position, salary_grade, salary, CURRENT_TIMESTAMP FROM app_interview t GROUP BY atname HAVING COUNT(DISTINCT atic)");
}
}
?>
$query = 7 means you are assigning value 7 to variable $query
In order to compare you have to use double equal sign ==
or triple equal signs === for same data type.
if($query = 7)
means you assign $query is 7 and it will always true and always executed, you can try this
if( $query == 7 )
That means if $query value is equal to 7 or not
I have a PHP file that encodes Json data and when i view the JSON output when its a single data block i get a valid json code syntax this is an example :
single data block
But when the JSON results in a multiple data block it generates an invalid JSON format like this: multiple data blocks
This is my PHP code:
<?php
header('Content-Type: application/json; charset=utf-8', true,200);
DEFINE('DATABASE_USER', 'xxxxx');
DEFINE('DATABASE_PASSWORD', 'xxxxxx');
DEFINE('DATABASE_HOST', 'xxxxxxxxxxx');
DEFINE('DATABASE_NAME', 'xxxxxxxx');
// Make the connection:
$dbc = #mysqli_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD,
DATABASE_NAME);
$dbc->set_charset("utf8");
if (!$dbc) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
if(isset($_GET['keyword'])){//IF the url contains the parameter "keyword"
$keyword = trim($_GET['keyword']) ;//Remove any extra space
$keyword = mysqli_real_escape_string($dbc, $keyword);//Some validation
$query = "select name,franco,alpha,id,url,songkey,chord from song where name like '%$keyword%' or franco like '%$keyword%'";
//The SQL Query that will search for the word typed by the user .
$result = mysqli_query($dbc,$query);//Run the Query
if($result){//If query successfull
if(mysqli_affected_rows($dbc)!=0){//and if at least one record is found
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ //Display the record
$data = array();
$data = $row;
echo $_GET[$callback]. ''.json_encode($data).'';
}
}else {
echo 'No Results for :"'.$_GET['keyword'].'"';//No Match found in the Database
}
}
}else {
echo 'Parameter Missing in the URL';//If URL is invalid
}
?>
It is because you are JSON-encoding a single line of the result set at at time. This is not a valid JSON structure if the calling client is expecting such.
Likely, you will want to put each row as an entry in an array, and then JSON-encode and echo the resulting array.
Like this:
if($result){//If query successfull
if(mysqli_affected_rows($dbc)!=0){//and if at least one record is found
$array = array();
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ //Display the record
$array[] = $row;
}
echo json_encode($array);
}
}