I am having issue with spinner populating from PHP. I have MySQL table with cities and classes. I need to take classes from specific sities. PHP for cities looks like this:
{"lista":[{"City":"Beograd"},{"City":"Novi Sad"},{"City":"Kragujevac"}]}
and when I try to populate spinner with classes from "Novi Sad" I am getting error in android
08-09 09:53:37.762: E/Fail 1(28592): java.lang.IllegalArgumentException: Illegal character in query at index 50: http://192.168.1.2/test/test.php?city=Novi%20Sad
If I call http://192.168.1.2/test/test.php?grad=Novi%20Sad in my localhost I am getting {"lista":[{"Class":"matematika"},{"Class":"informatika"}]}. If I try to populate spinner with City: Beograd or Kragujevac everything is working fine. I am guessing that problem is in empty space between Novi and Sad.
Url for populating spinner2 from spinner1(Cities):
str_grad1=spinner1.getSelectedItem().toString();
String url="http://192.168.1.2/test/test.php?grad="+str_grad1;
EDIT: Here is also PHP script
$con = mysqli_connect($host, $user, $pwd, $db);
if(mysqli_connect_errno($con)) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
$sql = "SELECT Predmet FROM lista where City='".$_GET['grad']."'";
$result = mysqli_query($con, $sql);
$rows = array();
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$rows[] = $row;
}
mysqli_close($con);
$arr = array_flip(array_map('serialize', $rows));
$lista = array_map('unserialize', array_flip($arr));
echo json_encode((object) array('lista' => array_values($lista)));
Shouldn't you encode str_grad1 like
String url="http://192.168.1.2/test/test.php?grad=" + URLEncoder.encode( str_grad1 );
instead of:
String url="http://192.168.1.2/test/test.php?grad="+str_grad1;
Related
Apologies as this is probably very basic. I have created a SELECT query and have (I think) stored the data retrieved as an array.
By myself I have been able to use printf to output selected items from the array but I want to output the values in a more structured way, as an unordered list in HTML. It's going to be a list of links. anchor corresponds to the link name column in my MySQL table and link corresponds to the url column, to be output as, e.g
<li>anchor</li>
This is as far as I have got. I know I need a for loop but the demos I've copied keep failing.
Very grateful for any pointers from kind people. Backend is new to me.
<?php
$server = "localhost";
$username = "blah";
$password = "blahblah";
$database = "blah_db";
$conn = mysqli_connect($server, $username, $password, $database);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$result = mysqli_query($conn, "SELECT anchor, link FROM footerLinks");
while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
printf("Anchor: %s Link: %s ", $row[0], $row[1]);
}
mysqli_free_result($result);
?>
There is not much to change in your code. Add <ul> and </ul> around the while loop. Change the pattern to <li>%s</li>. And swap $row[0], $row[1] to $row[1], $row[0]:
$result = mysqli_query($conn, "SELECT anchor, link FROM footerLinks");
echo '<ul>';
while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
printf('<li>%s</li>', $row[1], $row[0]);
}
echo '</ul>';
I would though use MYSQLI_ASSOC instead of MYSQLI_NUM (which is considered bad practice), and also use the object oriented style for mysqli functions:
$result = $conn->query("SELECT anchor, link FROM footerLinks");
echo '<ul>';
while ($row = $result->fetch_assoc()) {
printf('<li>%s</li>', $row['link'], $row['anchor']);
}
echo '</ul>';
I am still new to PHP. I have tried a few stuff, but I just can't get it to work.
Question: I want all the data from my users table to be in a string, separated by comma. Then when the ID is 2 to be ; for net new row, so on and so forth. If someone can please help me.
$server = "localhost";
$user_name = "root";
$password = "";
$database = "users";
$conn = new mysqli($server, $user_name, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM Users;";
$result = $conn ->query($sql);
while($row = mysqli_fetch_array( $result )) {
$rows = implode (";",$result);
$array = $rows;
echo $array;
}
Question2: But if I want first row of DB data to be, separated and then at the end with a ;. How would I do that?
Output: The output of this code is:
Warning: implode(): Invalid arguments passed
You've simply used the wrong variable in your call to ìmplode.
You've assigned all the columns as an array to $row - but you're trying to implode $result.
Update that line to this:
$rows = implode(";", $row);
Let's say your user table has 2 fields Firstname and Lastname. What I understood from your question is you want your output to be something like
$array = ['steve,jobs;', 'mark,zukerberg;'];
To achieve this you can append ';' at the end of the string.
while($row = mysqli_fetch_array( $result )) {
$rows = implode(',',$row) . ';'; //you have named this variable $rows but it is going to have data of a single row
$array = $rows; //you could directly var_dump($rows) instead of assigning it to a new variable
echo $array; //you could rather use var_dump($array) for this
}
I have a database from which I retrieve information successfully.
//Connect to mysql database
$con = mysqli_connect($host,$user,$pass);
mysqli_select_db($con, $databaseName);
//Query database for data
$sql = "SELECT * FROM donators";
$result = mysqli_query($con, $sql);
I can send it to my browser by iterating print_r($row)
//this returns the result
while($row = mysqli_fetch_array($result))
{
print_r($row);
}
But when I try to retrieve it by iterating $row['lastName'] it does not return anything at all. It works on all other rows. This specific row contains peoples lastName. I am also 100% certain I wrote 'lastName' right.
//no result here but woudl work without "firstName"=>$row['firstName']
while($row = mysqli_fetch_array($result))
{
$output[]= array( "index"=>$row['index'], "firstName"=>$row['firstName'], "lastName"=>$row['lastName']);
}
echo json_encode($output);
Anyone has an idea what can be / is causing this?
I have some problems with json..
I will let my code here, and i will show you what does it print to me, and what i need to be printed..
Well... this is my code:
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","3d") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$query = "SELECT team FROM hs";
$result = mysqli_query($connection, $query) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$arr = array();
while($row =mysqli_fetch_assoc($result))
{
$arr[] = $row;
}
echo json_encode($arr);
//close the db connection
mysqli_close($connection);
And it print me a json code, like:
[{"team":"coco"},{"team":"dada"},{"team":"fafa"},{"team":"momo"}]
My question is, how can i print a json code like this:
{"team":[["coco"],["dodo"]...]}
Another question is, how can i print a json code like this: (I want to group 2 teams, like a power of 2...
{"team":[["coco","dada"],["fafa","momo"]]}
Thank you, and have a nice day...
You need to form a proper array in your php
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","3d") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$query = "SELECT team FROM hs";
$result = mysqli_query($connection, $query) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$arr = $new_arr = array();
while($row =mysqli_fetch_assoc($result))
{
$arr[] = $row['team'];
}
shuffle($arr);
$new_arr['team'] = array_chunk($arr, 2);
echo json_encode($new_arr);
//close the db connection
mysqli_close($connection);
The thing that is getting printed is a json array which consists of JSON objects hence you see the result like:
[{"team":"coco"},{"team":"dada"},{"team":"fafa"},{"team":"momo"}]
What I would suggest is, you should create a json array and keep adding json objects to it.
JSONArray team = new JSONArray();
team.add("coco");
team.add("dodo");
and so on.
Coming to your second doubt, create json arrays which will contain pairs of elements such as coco and dodo in one, foo and bar in other. Let's call these arrays arr1 and arr2.
Now create the main JSON array named team and do the following:
team.put(arr1);
team.put(arr2);
And you'll see the result you want. Do ask for clarifications if any. :)
I've been searching for this everywhere, but still can't find a solution: How do I get all the values from a mySQL column and store them in an array?
For eg:
Table Name: Customers
Column names: ID, Name
# of rows: 5
I want to get an array of all the 5 names in this table. How do I go about doing that? I am using PHP, and I was trying to just:
SELECT names FROM Customers
and then use the
mysql_fetch_array
PHP function to store those values in an array.
Here is a simple way to do this using either PDO or mysqli
$stmt = $pdo->prepare("SELECT Column FROM foo");
// careful, without a LIMIT this can take long if your table is huge
$stmt->execute();
$array = $stmt->fetchAll(PDO::FETCH_COLUMN);
print_r($array);
or, using mysqli
$stmt = $mysqli->prepare("SELECT Column FROM foo");
$stmt->execute();
$array = [];
foreach ($stmt->get_result() as $row)
{
$array[] = $row['column'];
}
print_r($array);
Array
(
[0] => 7960
[1] => 7972
[2] => 8028
[3] => 8082
[4] => 8233
)
Note that this answer is outdated! The mysql extension is no longer available out of the box as of PHP7. If you want to use the old mysql functions in PHP7, you will have to compile ext/mysql from PECL. See the other answers for more current solutions.
This would work, see more documentation here :
http://php.net/manual/en/function.mysql-fetch-array.php
$result = mysql_query("SELECT names FROM Customers");
$storeArray = Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[] = $row['names'];
}
// now $storeArray will have all the names.
I would use a mysqli connection to connect to the database. Here is an example:
$connection = new mysqli("127.0.0.1", "username", "password", "database_name", 3306);
The next step is to select the information. In your case I would do:
$query = $connection->query("SELECT `names` FROM `Customers`;");
And finally we make an array from all these names by typing:
$array = Array();
while($result = $query->fetch_assoc()){
$array[] = $result['names'];
}
print_r($array);
So what I've done in this code:
I selected all names from the table using a mysql query. Next I use a while loop to check if the $query has a next value. If so the while loop continues and adds that value to the array '$array'. Else the loop stops. And finally I print the array using the 'print_r' method so you can see it all works. I hope this was helpful.
Since mysql_* are deprecated, so here is the solution using mysqli.
$mysqli = new mysqli('host', 'username', 'password', 'database');
if($mysqli->connect_errno>0)
{
die("Connection to MySQL-server failed!");
}
$resultArr = array();//to store results
//to execute query
$executingFetchQuery = $mysqli->query("SELECT `name` FROM customers WHERE 1");
if($executingFetchQuery)
{
while($arr = $executingFetchQuery->fetch_assoc())
{
$resultArr[] = $arr['name'];//storing values into an array
}
}
print_r($resultArr);//print the rows returned by query, containing specified columns
There is another way to do this using PDO
$db = new PDO('mysql:host=host_name;dbname=db_name', 'username', 'password'); //to establish a connection
//to fetch records
$fetchD = $db->prepare("SELECT `name` FROM customers WHERE 1");
$fetchD->execute();//executing the query
$resultArr = array();//to store results
while($row = $fetchD->fetch())
{
$resultArr[] = $row['name'];
}
print_r($resultArr);
First things is this is only for advanced developers persons Who all are now beginner to php dont use this function if you are using the huge project in core php use this function
function displayAllRecords($serverName, $userName, $password, $databaseName,$sqlQuery='')
{
$databaseConnectionQuery = mysqli_connect($serverName, $userName, $password, $databaseName);
if($databaseConnectionQuery === false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
return false;
}
$resultQuery = mysqli_query($databaseConnectionQuery,$sqlQuery);
$fetchFields = mysqli_fetch_fields($resultQuery);
$fetchValues = mysqli_fetch_fields($resultQuery);
if (mysqli_num_rows($resultQuery) > 0)
{
echo "<table class='table'>";
echo "<tr>";
foreach ($fetchFields as $fetchedField)
{
echo "<td>";
echo "<b>" . $fetchedField->name . "<b></a>";
echo "</td>";
}
echo "</tr>";
while($totalRows = mysqli_fetch_array($resultQuery))
{
echo "<tr>";
for($eachRecord = 0; $eachRecord < count($fetchValues);$eachRecord++)
{
echo "<td>";
echo $totalRows[$eachRecord];
echo "</td>";
}
echo "<td><a href=''><button>Edit</button></a></td>";
echo "<td><a href=''><button>Delete</button></a></td>";
echo "</tr>";
}
echo "</table>";
}
else
{
echo "No Records Found in";
}
}
All set now Pass the arguments as For Example
$queryStatment = "SELECT * From USERS ";
$testing = displayAllRecords('localhost','root','root#123','email',$queryStatment);
echo $testing;
Here
localhost indicates Name of the host,
root indicates the username for database
root#123 indicates the password for the database
$queryStatment for generating Query
hope it helps
PHP 5 >= 5.5.0, PHP 7
Use array_column on the result array
$column = array_column($result, 'names');
How to put MySQL functions back into PHP 7
Step 1
First get the mysql extension source which was removed in March:
https://github.com/php/php-src/tree/PRE_PHP7_EREG_MYSQL_REMOVALS/ext/mysql
Step 2
Then edit your php.ini
Somewhere either in the “Extensions” section or “MySQL” section, simply add this line:
extension = /usr/local/lib/php/extensions/no-debug-non-zts-20141001/mysql.so
Step 3
Restart PHP and mysql_* functions should now be working again.
Step 4
Turn off all deprecated warnings including them from mysql_*:
error_reporting(E_ALL ^ E_DEPRECATED);
Now Below Code Help You :
$result = mysql_query("SELECT names FROM Customers");
$Data= Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$Data[] = $row['names'];
}
You can also get all values in column using mysql_fetch_assoc
$result = mysql_query("SELECT names FROM Customers");
$Data= Array();
while ($row = mysql_fetch_assoc($result))
{
$Data[] = $row['names'];
}
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.
Reference
YOU CAN USE MYSQLI ALTERNATIVE OF MYSQL EASY WAY
*
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
$result=mysqli_query($con,$sql);
// Numeric array
$row=mysqli_fetch_array($result,MYSQLI_NUM);
printf ("%s (%s)\n",$row[0],$row[1]);
// Associative array
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
printf ("%s (%s)\n",$row["Lastname"],$row["Age"]);
// Free result set
mysqli_free_result($result);
mysqli_close($con);
?>