I am trying to fetch three columns from the MySql database. I am able to fetch the contents but this is not what I need. I need only the contents as a string array so that I can use them to populate list view in my java code.
The current response from my script is:
{ ["UID"]=> string(1) "1" ["UserName"]=> string(7) "abc#123" ["Subject"]=> string(15) "My Android Post"}object(stdClass)#4 (3) { ["UID"]=> string(1) "2" ["UserName"]=> string(7) "abc#123" ["Subject"]=> string(15) "My Android Post"}
I need some thing like as shown below in a String array or a list:
1 abc#123 My Android Post
2 abc#123 My Android Post
How can I get only the value stored in the column in PHP. I am new to PHP scripts, so please help me in solving this issue.
My current PHP script is as shown below:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "iFocusBlogs";
$obtainedUserName = 1;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql="SELECT UID, UserName, Subject FROM AndroidTable WHERE Status ='" .$obtainedUserName. "'";
$result=mysqli_query($conn,$sql);
while($obj = $result->fetch_object()){
var_dump($obj);
}
$conn->close();
?>
Please let me know what change do I need to make in the script to get only the contents of the columns. All suggestions are welcome. Thanks in Advance.
You can also use mysqli_fetch_row()
/* fetch associative array */
while ($row = mysqli_fetch_row($result)) {
printf ("%s (%s)\n", $row[0], $row[1]).PHP_EOL;
}
Try this Updated
$query="SELECT UID, UserName, Subject FROM AndroidTable WHERE Status ='" .$obtainedUserName. "'";
if ($result = $conn->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["UID"], $row["UserName"],$row["Subject"]);
}
}
You can access object '->' symbol
$tCont="";
while($obj = $result->fetch_object()){
//var_dump($obj);
$tCont.='<tr><td>'.$obj->UID.'</td><td>'.$obj->UserName.'</td><td>'.$obj->Subject.'</td></tr>';
}
echo $tCont;
Use fetch_array instead of fetch_object.
You might need some additional modifications to get the array exactly as you want, but at least it's a lot closer.
If you specify MYSQL_NUM as second parameter, you will get an array without keys and just numeric indexes. That array is clean enough to process further.
You can output the array using a for loop...
foreach($array as $item) {
echo $item . '<br>';
}
or use implode()...
echo implode($array);
or use json_encode()...
echo json_encode($array);
It all depends how exactly you want to show your array.
Functions like print_r and var_dump are useful for inspecting the contents of arrays and other variables, but are unlikely to output that content in a format that is usable by external programs.
change your select statement, probably concatenate the columns:
$sql="SELECT CONCAT (UID,' ' , UserName,' ', Subject) AS myresult FROM AndroidTable WHERE Status =" . $obtainedUserName ;
$result = $conn->query($sql);
use fetch_assoc and print each row:
while($row = $result->fetch_assoc()){
echo $row['myresult'];
}
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 have a MySQL database and am trying to print out the contents of specific rows. For some reason echo $row[1]; prints out the contents of row 1 perfectly, but I'm unable to do the same for the other rows (echo $row[2];, echo $row[3];, etc). The table has a unique index column with four rows labeled 1-4.
What I'd eventually like to do is print out just the contents of the last row, which I thought would look something like echo $row['$maxrows']; however I can't even get the syntax for printing any row past 1!
I think that this may be an issue with my table, but can't quite see what it is as there is an index column. Any suggestions or pointers would be appreciated?
What might I do to echo rows in my table past row 1?
UPDATE
var_dump($row); returns the below
{ [0]=> string(1) "1" ["Index"]=> string(1) "1" [1]=> string(121) "https://www.tilley.com/media/catalog/product/cache/image/1100x1100/e9c3970ab036de70892d86c6d221abfe/t/t/ttw2_black2_a.jpg" ["Sketch"]=> string(121) "https://www.tilley.com/media/catalog/product/cache/image/1100x1100/e9c3970ab036de70892d86c6d221abfe/t/t/ttw2_black2_a.jpg" }
The table has two columns:
1-Name: Index - int(11) - AUTO_INCREMENT
2-Name: Sketch - text
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM Table";
$result = mysqli_query($conn, $sql);
$maxrows = mysqli_num_rows($result);
//$result = $conn->query("SELECT * FROM Table");
$row = $result->fetch_array(MYSQL_BOTH);
echo $maxrows;
echo $row[1];
echo $row[2];
echo $row[3];
echo $row[4];
//echo $result;
$conn->close();
Your result array has 4 keys: 0, Index, 1 and Sketch, that's the results of the first row only. You're querying 2 columns but try to access 4 columns. Column numbering starts with 0. And you're not iterating the result rows. That $row = $result->fetch_array(MYSQL_BOTH); should be in a loop.
Turn on error reporting. PHP would show you which undefined variables your accessing.
Use PDO in favor to mysqli.
Don't create an array with both column name indexes and numeric indexes (don't use MYSQL_BOTH). Use PDO::FETCH_ASSOC or PDO::FETCH_NUM.
Start using var_dump() instead of echo for debugging. Always.
Use a foreach loop when processing the result array.
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
I have currently a php script as given below:
<?php
$con=mysqli_connect("localhost","username","password","temp");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = mysqli_real_escape_string($con, $_POST['username']);
$result = mysqli_query($con,"SELECT imagename FROM table3 where username='$username'");
$rows = array();
while($r = mysqli_fetch_assoc($result))
{
$rows[] = $r;
}
echo json_encode($rows);
mysqli_close($con);
?>
The output which I get after running this script is in the form given below:
[{"imagename":"1"},{"imagename":"2"}]
But I need a string in a format like this as my output:
{"Android":[{"imagename":"1"},{"imagename":"2"}]}.
That is, I should be able to add the string {"Android": to the beginning of my actual output and add the string } to the ending part of my actual output.
So what code should I need to add extra to obtain like the above format. Can someone please help me out.. Thanks in advance..
try this by defining your key in the array of $rows you should get your result you want.
{
$rows['Android'] = $r;
}
I'd really like some help with the following MySQL / PHP problem (maybe bug?)
I'm trying to retrieve and display an array of data from my database using MySQL / PHP, but when I echo out the array, it returns the first value as 'null'.
So, even though the database has the following info:
"Example 1", "Example 2", "Example 3"...
The php echos out:
"null", "Example 2, "Example 3"
I would imagine this would be a common problem, but I haven't managed to find the required information elsewhere on the internet, so I'm hoping you kind folks can help.
My PHP
/* If connection to database, run sql statement. */
if ($conn) {
$fetch = mysql_query("SELECT column FROM table WHERE approved = '1' ");
// declare empty array to fill later
$result = array();
// make sure the MySQL pointer is looking at the first row
mysql_data_seek($fetch, 0);
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
foreach ($row as $value) {
$row_array = $value;
// push info into new array with just the value
array_push($result, $row_array);
}
}
}
/* Free connection resources. */
mysql_close($conn);
/* Toss back results as json encoded array. */
echo json_encode($result);
UPDATE
New code courtesy of Mark B:
if ($conn)
{
$sql = "SELECT column_name FROM table WHERE comment_approved = '1' ";
$query = mysql_query($sql) or die(mysql_error());
$result = array();
while ($row = mysql_fetch_assoc($query)) {
$result[] = $row['column_name'];
}
}
/* Free connection resources. */
mysql_close($conn);
/* Toss back results as json encoded array. */
echo json_encode($result);
NOTE:
The 'null' problem still occurs with or without the:
mysql_data_seek($fetch, 0);
as that appears to do nothing.
Any help would be great!
SOLVED
Thanks to Mark B who pointed out that the problem was probably in the database rather than the PHP, it turned out there was the character ` lurking where there should have been a '. This caused the information to appear 'null'.
$sql = "SELECT column FROM table WHERE approved = '1'";
$result = mysql_query($sql) or die(mysql_error());
$data = array();
while($row = mysql_fetch_assoc($result)) {
$data[] = $row['column'];
}
echo json_encode($data);
You shouldn't have to do the seek, as you've not done anything with the result at the time. And since you're only fetching a single column from the database, there's no need for the inner foreach() loop either.
Try removing the call to mysql_data_seek. I see no reason why the MySQL pointer wouldn't already point to the first row at the first call to mysql_fetch_array.
You could try removing mysql_data_seek($fetch, 0); as the pointer will already be on the first record if you have just made the query.