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.
Related
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
}
Is it possible to construct a loop which takes every single value from an array and then updates a mysql table?
What the array looks like
output
Team Blue
4
4
Team Red
4
4
Bare in mind that the 4's are Id's.
Array code
$players = $lista;
shuffle($players);
$player_count = count($players);
$players_per_team = $player_count/2;
$teams = array_chunk($players,$players_per_team);
$team_1 = $teams[0]; // Lag 1
$team_2 = $teams[1]; // Lag 2
echo "Team Blue";
echo "<br>";
foreach ($team_1 as $value) {
echo $value . "<br>";
}
echo "<br>";
echo "Team Red";
echo "<br>";
foreach ($team_2 as $value) {
echo $value . "<br>";
}
How can i select each element in the array?
Basically all i need to do is to update a single column for each id in both arrays.
See picture
https://gyazo.com/ceb49db66ba85b9a6adfa0daf30c7a57
I want to update "team" column.
My guess is that i need to make some sort of loop, but i have no clue on how to select each element and then querying it.
So my question is.
How can i select each element in the array and loop some sort of query to update a single column?
If i need to provide more information, just tell me!
Thank you for taking your time reading my question, kind regards Jonas
Google is your friend:
"php mysqli update column"
Best Result: https://www.w3schools.com/php/php_mysql_update.asp
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
Before you update or insert data check if your value are a integer
if (is_numeric($myArr[0])) {
// number
} else {
// something other
}
I think this question is going to be rather interesting. So, as the title suggests, I am trying to make a dynamic select field. Basically, when the time comes my web app will connect to my database, and pull the entire row that matches my query. My question is this: How can I present the data from ONE of the columns within the row as INDIVIDUAL options within the select tag? This is what I am trying right now:
<select>
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "people";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}else{
$search_query = "SELECT * FROM people_list WHERE person_id = $_SESSION[person_id]";
$result = $conn->query($search_query);
while($person_result_list = mysqli_fetch_assoc($result)){
echo "
<option value='$result[person_result_list]'>'$result[person_name]', '$result[person_result_list]'</option>
";
}
}
?>
</select>
This is returning an error:
Cannot use object of type mysqli_result as array
Which should be pretty straight forward to fix, but I just can't figure out the workaround to this. Any ideas?
Thanks all!
Cannot use object of type mysqli_result as array
That's because of this statement,
<option value='$result[person_result_list]'>'$result[person_name]', '$result[person_result_list]'</option>
^^^^^^^ ^^^^^^^ ^^^^^^^
$result is a MySQLi result object, not an array.
My question is this: How can I present the data from ONE of the columns within the row as INDIVIDUAL options within the select tag?
Simply fetch the row the result set and use foreach loop to display each individual column value inside <option> element, like this:
// your code
$search_query = "SELECT * FROM people_list WHERE person_id = $_SESSION[person_id]";
$result = $conn->query($search_query);
$person_result_list = mysqli_fetch_assoc($result)
foreach($person_result_list as $value){
echo '<option value="' . $value . '">' . $value . '</option>'
}
// your code
you can use GROUP_CONCAT in the query. It will return you a comma separated string of the values of your target column only. You then can split this string to make it an array to use for the select dropdown.
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 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'];
}