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
}
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 newbie to PHP and need to seek your help on how to populate the array which is $dataArray[] with the rows of MySQL so that I will be able to call the data Array in some other function or say I want to print the $dataArray as above. I would be thankful to you if you can provide me example code modifications in my below code
<?php
$dataArray=array();
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT reg_date,xyz,pqr FROM stuvw";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
$test = mysqli_num_rows($result);
echo $test;
while($row = mysqli_fetch_assoc($result))
{
$populate = '"' . $row["reg_date"]. '"'."=>" . $row["xyz"]. ", " ;
$dataArray[$populate] = $test;
}
echo $dataArray[$populate];
}
mysqli_close($conn);
?>
You can use an Associative array. This stores the data in a key-value format.
$dataArray[ $row['reg_date'] ] = $row['xyz'];
What you are doing in you example is creating a string in the $populate variable and using it as a key in the $dataArray. The number of rows returned from the SQL query is then stored as the value for each item in the $dataArray. This number is in the $test variable.
The key needs to be unique however so it makes sense to use the primary key from your MYSQL result as you key (if necessary).
Have a read through W3Schools PHP course.
http://www.w3schools.com/php/php_arrays.asp
<?php
$username = "trainerapp";
$password = "password";
$hostname = "localhost";
$link = #mysql_connect($hostname, $username, $password);
if (#mysql_select_db("trainer_registration")) {
$select_query_num = #mysql_query("select id from program_details");
$num_rows = #mysql_num_rows($select_query_num);
while ($row = #mysql_fetch_assoc($select_query_num)) {
$j = $row['id'];
$select_query = #mysql_query("select id,program_name,company,date_prog from program_details where id = $j");
$fetch_query = #mysql_fetch_assoc($select_query);
$id = $fetch_query['id'];
$pgmname = $fetch_query['program_name'];
$comp = $fetch_query['company'];
$datephp = $fetch_query['date_prog'];
$arr[] = array(
$id,
$pgmname,
$comp,
$datephp
);
}
echo json_encode($arr);
}
?>
CURRENT OUTPUT:
[["1","Sample","Apple","2015-05-27"],["2","Sample 2","Lenovo","2015-05-28"],["14","3","3","09-29-2015"]]
I don't understand this output.
Questions:
What does json_encode actually return? A string of all values or an array separated by ','? Because when I tried str.length() in js file, it returned 126
How do I get output like single rows
["1","Sample","Apple","2015-05-27"]
["2","Sample 2","Lenovo","2015-05-28"]
["14","3","3","09-29-2015"]
in an array in javascript because I need to insert them in html under separate columns. That is, 1,2,14 under the column "ID", sample, sample 2, 3 under the column "Program name", and so on.
Please help on parsing this array.
1 - http://php.net/manual/en/function.json-encode.php all is detailled there.
2 - Convert php array to Javascript it will help you.
3 - If you need an array, why do you use json_encode in your code.
4 - Do you know why do you use # in many places? It's really bad to code like this.
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;
I have previously constructed an array manually, e.g.:
<?php
$noupload = array('nick', 'cliff');
?>
but now I am trying to populate the array automatically from users in a MySQL database. So far I have this:
<?php
// Make a MySQL Connection
$debug=false;
$conn = mysql_connect("host","user","password"); // your MySQL connection data
$db = mysql_select_db("database");
$query = "SELECT * FROM users WHERE access LIKE '%listen%'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$listen = "'". $row['login']. "', ";
}
?>
$listen constructs the user list in the way that I previously entered it manually (I tested this using echo), but I am not sure how to pass this to $noupload. I tried:
$noupload = array($listen);
but this didn't work. I think I'm close and would be grateful for some help over the final hurdle,
Thanks,
Nick
You can declare $listen as an array
$listen = array();
while ($row = mysql_fetch_array($result)) {
$listen[] = "'". $row['login']. "'";
}