got stuck converting MySql output in JSON array with php - php

I am making an iphone app. a part of that app allows users to search for a company on location.
I have a MySql database containing the companies that can be searched for, and a php file on my website to receive the searched data, and to return the companyName and companyLocation for all the found companies to my app. it looks like this:
<?php
if (isset($_GET["companyCitySearchField"])){
$companyCity = $_GET["companyCitySearchField"];
$result = search($companyCity);
echo $result;
}
function makeSqlConnection()
{
$DB_HostName = "******";
$DB_Name = "*******";
$DB_User = "*******";
$DB_Pass = "*******";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
return $con;
}
function disconnectSqlConnection($con)
{
mysql_close($con);
}
function search($companyCity)
{
$con = makeSqlConnection();
$query = mysql_query("SELECT companyName, companyCity from Company WHERE companyCity = '$companyCity'");
$companies = array();
while ($row = mysql_fetch_assoc($query)) {
$companies['companies'][] = $row;
print json_encode($companies);
}
disconnectSqlConnection($con);
}
?>
this works fine when only one company is found. it gives me a perfect JSON array:
{"companies":[{"companyName":"Dijkstra","companyCity":"Geldermalsen"}]}
everything fine so far.
Now, I create another company in my database, also with Geldermalsen as location.
2 companies are found in the database now. the JSON array it return now, doesn't make sense:
{"companies":[{"companyName":"Dijkstra","companyCity":"Geldermalsen"}]}{"companies":[{"companyName":"Dijkstra","companyCity":"Geldermalsen"},{"companyName":"testaccount","companyCity":"Geldermalsen"}]}
for some reason, it seems to make 2 separate array's. one for the first found company, and one with both.
I have been searching the web, stackoverflow, google and even the book 'PHP and MySql for dummies' for days, and I have changed my code numerous times, and whatever I try it keeps on doing this.
Does anyone know what I should do to get one array containing all found companies with this script, instead of these 2?
any help would be very welcome, Thank you in advance!

You are echoing out JSON for each row, not for the fully built array. Move your print statement outside the loop.
$companies = array();
while ($row = mysql_fetch_assoc($query)) {
$companies['companies'][] = $row;
}
print json_encode($companies);
Or better yet, you might not want to echo out anything at all in the search function, but leave that up to the caller. It seems you already might be intending to do this here:
$result = search($companyCity);
echo $result;
The only problem is that the search() function doesn't return any value so $result would be null. You should make up your mind about where you are going to echo the result to the client and be consistent about it.

Related

Unique page for each row in database with PHP

I have been trying to create a unique page for each row in my database. My plan is to create a dictionary.php?word=title url, where I can display the description and title of that specific ID. My datbase is contains id, term_title and term_description.
I'm fresh outta the owen when it comes to PHP, but I've managed to atleast do this:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbname";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Cannot connect to database." . mysqli_connect_error());
}
if (isset($_GET['id']))
{
$id = (int) $_GET['id'];
$sql = 'SELECT * FROM dbname WHERE id = $id LIMIT 1 ';
}
$sql = "SELECT * FROM terms";
$result = $conn->query($sql);
mysqli_close($conn);
?>
I'm really stuck and I dont know what the next step is, I've added the <a href='dictionary.php?=".$row["id"]."'> to each word I want to be linked, and this is properly displayed in the main index.php file (where all my words are listed with <li>. This is my code for this:
<?php
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<a href='dictionary.php?=".$row["id"]."'><li class='term'><h4 class='term-title'>" . $row["term_title"]. "</h4></li></a>";
} else {
echo "No words in database.";
}
?>
How do I create this unique page, only displaying title and description for that id? How do I add ?word= to the url?
Thanks for taking your time to help me.
Update from years later: Please, please use parameters when composing your SQL queries. See Tim Morton's comment.
You're on the right track, and ajhanna88's comment is right, too: you want to be sure to include the right key ("word" in this case) in the URL. Otherwise, you're sending a value without telling the page what that value's for.
I do see a couple other issues:
When you click on one of the links you created, you're sending along $_GET["word"] to dictionary.php. In your dictionary.php code, however, you're searching for your word by "id" instead of by "word". I'm guessing you expect users to search your dictionary for something like "celestial" and not "1598", so try this instead:
if (isset($_GET['word'])) {
$word = $_GET['word'];
$sql = 'SELECT * FROM dbname WHERE word = $word LIMIT 1 ';
}
BUT! Also be aware of a security problem: you were letting the user put whatever they want into your query. Take a look at the classic illustration of SQL injection. To fix that, change the second line above to this:
`$word = $conn->real_escape_string($_GET['word']);`
Another problem? You're looking for the word exactly. Instead, you'll probably want to make it case insensitive, so "Semaphore" still brings up "semaphore". There are plenty of ways to do that. The simplest way in my experience is just changing everything to lowercase before you compare them. So that $word assignment should now look like this:
`$word = $conn->real_escape_string(strtolower($_GET["word"]));`
And your query should look something like this:
`$sql = "SELECT * FROM dbname WHERE word = LOWER('$word') LIMIT 1 ";`
Next! Further down, you overwrite your $sql variable with SELECT * FROM terms, which totally undoes your work. It looks like you're trying to show all the words if the user doesn't provide a word to look up. If that's what you're trying to do, put that line in an else statement.
Your $result looks fine. Now you just have to use it. The first step there is to do just like you did when you tested the connection query (if(!$conn)...) and check to see that it came back with results.
Once you have those results (or that one result, since you have LIMIT 1 in your query), you'll want to display them. This process is exactly what you did when printing the links. It's just that this time, you'll expect to have only one result.
Here's a real basic page I came up with from your code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbname";
$conn=new mysqli($servername,$username,$password,$dbname);
if($conn->connect_errno){
die("Can't connect: ".$conn->connect_error);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Dictionary!</title>
</head>
<body>
<?php
if(isset($_GET["word"])){
$word = $conn->real_escape_string(strtolower($_GET["word"]));
$sql = $conn->query("SELECT * FROM dictionary WHERE word=LOWER('".$word."') LIMIT 1");
if(!$sql){
echo "Sorry, something went wrong: ".$conn->error_get_last();
} else {
while($row=$sql->fetch_assoc()){
echo "<h2>".$row["word"]."</h2>";
echo "<p>".$row["definition"]."</p>";
}
}
} else {
$sql = $conn->query("SELECT word FROM dictionary");
if(!$sql){
echo "Sorry, something went wrong: ".$conn->error_get_last();
} else {
echo "<p>Here are all our words:</p><ul>";
while($row=$sql->fetch_assoc()){
echo "<li>".$row["word"]."</li>";
}
}
echo "</ul>";
}
?>
</body>
</html>
You should also take care to be consistent in your terminology. For this, my MySQL table had three columns: id, word, and definition. I dropped term since your URLs were using word. In my experience, it's best to keep the same terminology. It avoids confusion when your application gets more complicated.
Lastly, to answer your question about creating separate pages, you can see there that for a simple page like this, you may not need a separate page to display the definitions and the links -- just an if/else statement. If you want to expand what's in those if/else blocks, I'd suggest looking at PHP's include function.
You have a great start. Keep at it!

Data Management Issue - How to manage retrieved data from mysql?

I am developing a game(c#) with database(mysql) and web service(php) to retrieving the data. The issue is the data management. There is a table on database with the name of items and it has some columns like id, item_name, item_description, item_prop, update_date, ownerId. I added 70 items to this table manually. The users can also add some items to this table or they can update the items they have already added in the game. My purpose is retrieving the whole affected rows of the table when the user is first logged in and save it as a json file in the game folder. After, read that file to fill the game environment with those items.
I try a way to achieve this. Firstly, i hold an updateDate variable in the game which is past like "1990-05-10 21:15:43". Second, i send this variable to the webservice as '$lastUpdateDate'; and make a query according to that variable at the database. select * from channels where update_date >= '$lastUpdateDate'; and write these rows in a json file as items.json. after that make a second query to retrieve the time and refresh the updateDate variable in the game. select select now() as 'Result';. In this way user would not have to get the whole table and write in json file every login process. So, it would be good for the performance and the internet usage. The problem occurs when the users update an item which is already added before. I can see the updated item, too with the first query, but I wrote it in json file twice in this way.
php code part of the getItems of my loginuser.php :
<?php
include './function.php';
// CONNECTIONS =========================================================
$host = "localhost"; //put your host here
$user = "root"; //in general is root
$password = ""; //use your password here
$dbname = "yourDataBaseName"; //your database
$phpHash = "yourHashCode"; // same code in here as in your Unity game
mysql_connect($host, $user, $password) or die("Cant connect into database");
mysql_select_db($dbname)or die("Cant connect into database");
$op = anti_injection_register($_REQUEST["op"]);
$unityHash = anti_injection_register($_REQUEST["myform_hash"]);
if ($unityHash == $phpHash)
{
if($op == "getItems")
{
$lastUpdateDate = anti_injection_login($_POST["updateDate"]);
if(!$lastUpdateDate)
{
echo "Empty";
}
else
{
$q = "select * from items where update_date >= '$lastUpdateDate';";
$rs = mysql_query($q);
if (!$rs)
{
echo "Could not successfully run query ($q) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($rs) == 0)
{
echo "No rows found, nothing to print so am exiting";
exit;
}
$arr = array();
while ($row = mysql_fetch_row($rs))
{
$arr = $row;
}
echo json_encode($arr);
}
mysql_close();
}
}
?>
So, how can i solve this problem? Or do you have any better idea for this approach. Help would be much appreciated. Thank you for your time.

How do I retrieve a specific value from MySQL with PHP?

Okay I'm so fed up. I've spent the better part of my free time for the past week trying to figure this out. I know that the query has changed in SQL but I cant figure it out. All of the other posts I can find seem to be outdated. If anyone could help me out I would really appreciate it.
All I am trying to do is retrieve the id of a row by using a unique "passphrase" that I manually entered into a database and then set that as session data so that I can use that data on other pages. I feel like it shouldn't be this hard.
For demostration purposes here is my code using the older mysql_query.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'test321';
$db = 'local_test';
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($db); ?>
<?php
include 'includes/connection.php';
$pass = $_POST['inputPass'];
if(!$_POST['submit']) {
echo "please fill out the form";
header ('location: user_authenticate.php');
}
$query = "SELECT id FROM users WHERE pass= '$pass'";
$id = mysql_query($query);
$_SESSION["userId"] = "$id";
print $pass;
print $id;
print $_SESSION["userId"];?>
I've tried a lot of things so I've gotten a lot of different errors. I am hoping someone could point me in the right direction here. What is the best way to do this?
First off, don't use the mysql API; it's deprecated and won't work in PHP 7.
Now that that's out of the way, mysql_query() returns a result set resource (which is like an object) which can contain multiple rows which can contain multiple columns. To access the contents of this resource, you have to fetch a row into an array and then index into that array for the column you want. You need to do something like this:
$query = "SELECT id FROM users WHERE pass= '$pass'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$id = $row['id'];
and then you can use the value of $id.
The same holds for mysqli::query(), which returns a mysqli_result object.

Make a json object properly by retrieving data by MYSQL

I am making a php project and I am currently hosted it in my local xammp server.
I need to connect this to an android application using volley library.
So I need to make a json object.In orders I have stored picture of the product and orders.php page that I retrieve it via orderno.
In orders.php page I can see all my orders with images.
When trying to make the json object I need get this image url.I try to get it via order no but all the times i can't get the correct url.
Can anyone tell me how to solve this?
This is for making that json object.
This is the link to the image current json which I got
I want to make my image URL like below image:
There were multiple issues with your PHP code. However, I tried the resolve most of them. Still if you see any issues let me know, I will try to help you. I will highlight the changes I did to the code, for you to understand.
Here goes the PHP code to retrieve values:
<?php
// array for JSON response
$response = array();
include("config.php");
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD) or die(mysqli_error());
$db = mysqli_select_db($con,DB_DATABASE) or die(mysqli_error());
$result = mysqli_query($con,"SELECT * FROM ORDERS");
if (!empty($result)) {
// check for empty result
if (mysqli_num_rows($result) > 0) {
// user node
$response["orderdata"] = array();
while($row = mysqli_fetch_array($result))
{
$orderdata = array();
$i = $row["ITEM_ID"];
$url = "http://localhost/Online_shopping/admin/'$i'.jpg";
$orderdata["url"] = $url;
$orderdata["item_id"] = $row["ITEM_ID"];
$orderdata["price"] = $row["PRICE"];
$orderdata["size"] = $row["SIZE"];
array_push($response["orderdata"], $orderdata);
}
// success
$response["response_code"] = 200;
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["response_code"] = 999;
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["response_code"] = 999;
// echo no users JSON
echo json_encode($response);
}
?>
You need to first setup a connection with your database which is located in a particular server.
Using that connection, you need to query in your table to get the data.
mysql_query, mysql_fetch_array is deprecated. You have to use mysqli instead of mysql.
Lastly, you can go through this post to learn simple basic operations using PHP.

mysqli_fetch_assoc doesnt return first row

sorry I am very new to PHP. This has probably been asked before but I am unable to get this code working, I am currently trying to check whether a user has logged in before but the mysqli_fetch_assoc only seems to pull through the second row, this query should only return one row so i only figured it out it was returning two when i added a duplicate to my DB. I have found similar questions and solutions but havent been able to figure it out.
Thanks in advance.
require_once 'login.php';
$db_server = mysqli_connect($db_hostname,$db_username,$db_password,$db_database);
$query = "SELECT * FROM users WHERE username = 'ben944' AND firstlogin = '0'";
$result = mysqli_query($db_server,$query);
if(!$result) {
echo "not working";
exit;
}
$row = mysqli_fetch_row($result);
while($row = mysqli_fetch_assoc($result))
{
print_r($row);
}
The separate $row = mysqli_fetch_row($result); line already fetches and removes the first row from the result before the while loop starts. That's why it's not printed by the while loop (which you have added for debugging purposes obviously).

Categories