Passing JSON to Array in PHP - php

I'm working on a filter in which results are filtered right away, I'm wondering if that may be the cause of the problem so I thought I would ask and see if anyone could give me a pointer on how to proceed.
<script>
var services = [
<?php
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "###";
$username = "###";
$dbname = "###";
//These variable values need to be changed by you before deploying
$password = "###";
$usertable = "###";
$url = "permalink";
$title = "Address";
$amount = "rent";
$id = "id";
$status = "Beds";
$nonprofit = "Address";
//Connecting to your database
mysql_connect($hostname, $username, $password) OR DIE ("He's dead Jim");
mysql_select_db($dbname);
//Fetching from your database table.
$query = "SELECT * FROM $usertable";
$result = mysql_query($query);
if ($result) {
while($row = mysql_fetch_array($result)) {
$url = $row["$url"];
$title = $row["$title"];
$amount = $row["$amount"];
$id = $row["$id"];
$status = $row["$status"];
$nonprofit = $row["$nonprofit"];
echo '{"permalink": "';
echo "{$url}";
echo '",';
echo '"title": "';
echo "{$title}";
echo '",';
echo '"amount":';
echo "{$amount}";
echo ',';
echo '"id": "';
echo "{$id}";
echo '",';
echo '"status": "';
echo "{$status}";
echo '",';
echo '"address": "';
echo "{$address}";
echo '",';
echo '},';
}
}
?>
]
//]]>
</script>
<script id="template" type="text/html">
<a title="{{title}}" href="{{permalink}}">
<div class="fs_box hide-for-small-down">
<div class="fs_left">
<span class="fs_head">{{title}}</span>
<span class="fs_id"><img src="images/{{id}}.jpg" width="75%" height="75%" onError="this.onerror=null;this.src='images/logo.png';"></span>
<span class="fs_status">{{status}}</span>
<span class="fs_disc">{{address}}</span>
</div>
<div class="fs_price">${{amount}}+</div>
<div class="clear"></div>
</div>
</a>
</script>
I'm expecting it to produce a bunch of results that then are filtered criteria which are elsewhere in the page.
When I try it currently just as a php code it outputs fine. However, when I try it in the php file that this should go in it produces nothing. Or does it dislike being in a script?
Thanks for any help!

You can use json_decode and json_encode to turn an array to json and json back to an array.
Also someone will probably mention that you should not be using the mysql_* functions in PHP as they are depreciated.
Something like this:
<?php
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "###";
$username = "###";
$dbname = "###";
//These variable values need to be changed by you before deploying
$password = "###";
$usertable = "###";
$url = "permalink";
$title = "Address";
$amount = "rent";
$id = "id";
$status = "Beds";
$nonprofit = "Address";
//Connecting to your database
mysql_connect($hostname, $username, $password) OR DIE ("He's dead Jim");
mysql_select_db($dbname);
//Fetching from your database table.
$query = "SELECT * FROM $usertable";
$result = mysql_query($query);
if ($result) {
$results = array()
while($row = mysql_fetch_array($result)) {
$results[] = $row;
}
$json = json_encode($results);
}
?>
]
<script>
var services = <?php echo $json; ?>;
</script>
This would give you a json object to use to render in your script.

What extension is the file you are saving?
If it's not .php or an extension set to render php, then you'll just have the code show up as test.
You might want to pull out the "die" statement after the db connect. This looks like you are running php in a .js file so you probably want the entire file to write out rather than stop because you couldn't connect to the database (or at least give 0 results, maybe a warning)

Related

php is not connecting with mysql

I want to perform a query on a database with genomic information.
This is part of the php code:
$db = mysqli_connect($servername,$username,$password,$database)
$fields = "name, chrom, strand, txStart, txEnd, exonCount, name2";
$query = "SELECT $fields FROM $table WHERE name2 LIKE '%$gene%';";
$result = mysqli_query($db,$query);
$items = mysqli_affected_rows($result);
if ($items == 0)
{
print_error("The gene $gene is not found in the RefSeq database");
}
else
{
$transcripts = $items;
echo "<html>\n";
echo "<head>\n";
echo "<title> Catalogue web server </title>\n";
echo "<link href=\"styles.css\" rel=\"stylesheet\">\n";
echo "</head>\n";
echo "<body>\n";
echo "<h1>Catalogue output ($gene)</h1>\n";
echo "<table>\n";
echo "<tr><th>GENE</th><th>TRANSCRIPTS</th><th>CHR</th><th>STRAND</th><th>POS1</th><th>POS2</th><th>EXONS</th>\n";
for ($i = 0; $i<$items; $i++)
{
$row = mysqli_fetch_array($result);
$name2 = $row["name2"];
$name = $row["name"];
$chrom = $row["chrom"];
$strand = $row["strand"];
$txStart = $row["txStart"];
$txEnd = $row["txEnd"];
$exonCount = $row["exonCount"];
echo "<tr><td>$name2</td><td>$name</td><td>$chrom</td><td>$strand</td><td>$txStart</td><td>$txEnd</td><td>$exonCount</td>\n";
}
echo"</table><br><br>\n";
}
However, when I submit the query from html localhost, I´m always getting the error message:
The gene is not in the database
When I know it is.
Any help finding the error would be appreciated it.
ALSO: $servername, $username, $password and $database are correct, checked several times
I don´t mind about mysql injections as I´m not publishing this web
Try instead with:
$items = mysqli_num_rows($result);
The mysqli_affected_rows is used after insert, update, replace or delete queries.

What did i do wrong? Html is confusing itself

I'm making a page where you have to enter a text in a textbox and the click send, another page will save it.
Also, on the first page, the text that was stored previously in the database, has to load. This is the code that i've got:
<?php
$databaseid = 3;
$servername = "jog4fun.be.mysql";
$username = "jog4fun_be";
$password = "****";
$dbname = "jog4fun_be";
$gettitel1 = null;
$gettext1 = null;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Id,Titel,Tekst FROM Teksten";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if ($row["Id"]== $databaseid ){
$gettitel1 = $row["Titel"];
$gettext1 = $row["Tekst"];
}
}
} else {
echo "0 results";
}
$conn->close();
$gettitel1 = strip_tags($gettitel1, '<br>');
$link1 = '<textarea id = "klein" rows="4" cols="50" name="titel3" form="usrform">' . $gettitel1 . '</textarea>';
$link2 = '<textarea id = "groot" rows="4" cols="50" name="text3" form="usrform">' . $gettext1 . '</textarea>';
echo $link1;
echo $link2;
?>
The problem is that it sends the text from textbox with name text3 as text1 with the post function. Can someone figure out what's wrong with it? I've been tying for an hour and i did not find it.
Thanks for your time and help,
Jonas
Simply here:
while($row = $result->fetch_assoc()) {
if ($row["Id"]== $databaseid ){
$gettitel1 = $row["Titel"];
$gettext1 = $row["Tekst"];
}
you overwrite the value of the two variables each time you iterate. So after this block of code you will keep stored the last values returned from the db.
YOu should add to your query a WHERE clause to identify the one and only record you need so you will fetch only the relevant data. Example:
$sql = "SELECT Id,Titel,Tekst FROM Teksten WHERE Id='1'";

Can we make database return something else,different from 0 when the field in empty

So my whole question in in the Title,but lets make it easier for you guys to understand.Now when there is an empty field in database php returns "0"There is an example:
I need when there is an empty spot this to be displayed,and by this i mean the "-" or "~" sign.
So is there way to make that automatic with PHP,when field is empty instead of "0" any symbol to be displayed,and if there is pleasee tell me <3
There is my Code:
<!--------------------------------------------------------------------------
PHP CODE
--------------------------------------------------------------------------->
<?php
$page_id= $_GET['id'];
$hostname = "localhost";
$username = "shreddin";
$password = "!utf55jyst";
$databaseName = "shreddin_nation";
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
$connect->set_charset("utf8");
$query = "SELECT * FROM food_data_bg where id = '" . $page_id . "'";
$result = mysqli_query($connect, $query);
?>
<?php while($row1 = mysqli_fetch_assoc($result)):; ?>
<?php
if (mysqli_num_rows($result) == 0){
echo "daaaaa";
}
$title= $row1['title'];
$fimage = $row1['fimage'];
$state = $row1['state'];
$carbs = $row1['carbohydrates'];
$proteins = $row1['proteins'];
$fats = $row1['fats'];
$caloriesTotal = $row1['calories total'];
$carbsCalories = $row1['carbs cal'];
$protCalories = $row1['prot cal'];
//and so on ...
//and after the all variables i am just displaying results in html elements like so
?>
<!--------------------------------------------------------------------------
HTML EXAMPLE
--------------------------------------------------------------------------->
<div class="food-macros"><b>Общи Калории</b><span><?php echo $caloriesTotal; ?></span></div>
<div class="food-macros"><b>Протеин</b><span><?php echo $proteins ?></span></div>
<div class="food-macros"><b>Въглехидрат</b><span><?php echo $carbs; ?></span></div>
<div class="food-macros"><b>Мазнини</b><span><?php echo $fats; ?></span></div>
Sorry if there is a mistake or something missing,i will fix and link everything you guys need to help me after get back from university,THANKS <3
for each item in your database you want to check if is ZERO (0):
$carbs = ($row1['carbohydrates'] === 0) ? "-" : $row1['carbohydrates'];
/// === means strictly same value
and so on...
EDIT:
function zeroField($field, $replace = "-")
{
return ($field === 0) ? $replace : $field;
}
usage:
$carbs = zeroField($row1['carbohydrates']); //output: "-" or field value
//or change sign
$carbs = zeroField($row1['carbohydrates'],"~"); //output: "~" or field value

avatar not being displayed json encode

As soon as i added .$thedatabase->displayavatar($username1,2). nothing is being displayed. It isn't a jQuery problem, so i haven't included that code. Why is it when i add that code nothing is returned with json_encode?
leaderboard.php
$thedatabase = new Database();
$thedatabase->opendb();
while($row = mysql_fetch_assoc($getleader)) {
$username1 = $row['username'];
$rating = $row['rating'];
$username = str_replace(' ','-',$username1);
$leaderboard[] = "<div class='leaderboard-user'><ul><li>".$thedatabase->displayavatar($username1,2)."</li><li><a>$username1</a></li><li>$rating</li></ul></div>";
}
$thedatabase->closedb();
echo json_encode($leaderboard);
displayavatar function in Database class
echo "<a href='/user/$user'><img src='/test.png' width='70px' height='70px' /></a>";
You're fetching the row
$username1 = $row['username'];
$rating = $row['rating'];
$username = str_replace(' ','-',$username1);
so your username is in $username, but for the funcion
$thedatabase->displayavatar($username1,2)
you are using the $username1, there's propably the empty char, and it can't make query
if it's not relevant for your query and there can be empty char, then sorry :))

I'm trying to retrieve data from mysql using php for my Flex Mobile application, but no luck

I am creating a login based application and this is what I have so far. I am trying to read each field into a separate textarea. I have tried to bind the data etc. I do get a output in the textarea, but it prints all the fields in one textarea. Please help.
<?php
selectDB();
function selectDB() {
$usertoken = $_POST['usertoken'];
//Database service vars
$databasehost = "localhost";
$databasename = "morerandom";
$databasetable = "random";
$databaseusername = "root";
$databasepassword = "root";
$con = mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());
$query = "SELECT username, useremail, firstname, lastname FROM $databasetable WHERE usertoken='$usertoken'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if ($count)
{
$rows = array();
while ($row = mysql_fetch_object($result)) {
$rows[] = $row;
}
echo $rows[0]->username . "\n";
echo "\n";
echo $rows[0]->useremail . "\n";
echo $rows[0]->firstname . "\n";
$first = $rows[0]->lastname;
echo $first;
// echo "$lastname;"
}
else
{
echo 'Token not valid';
}
mysql_free_result($result);
mysql_close($con);
}
?>
What you are getting is just one string. There are better way to retrieve this kind of data from the server side(XML or AMF).
If you want to go ahead with your method then split the string using '\n' as a delimiter but check first that the server response is not 'Token not valid'.
So something like this should work:
First remove the echo "\n"; line under the echo $rows[0]->username . "\n";
var responseArray:Array = theStringResult.split('\n');
So now the responseArray stores the username at position 0, useremail at position 1, firstname at position 2 and lastname at position 3.
But again, you are sending data from the server as raw text and this is not the best way to do it. Check this link to see how this can be done using AMFPHP.

Categories