Echo whole table without using column names as ref - php

Hi I really hope someone can help,
I have a table with one row and multiple column names, one of these being id, I want to echo the whole table without using the column names as reference as these might change and I don’t want to have to go in and change the code if a column gets added or taken away. i.e. I want to SELECT * from table WHERE id=1 then echo the whole table, not including the id column or any column titles.
I’m a bit stumped and not sure where to look for the right answer, hopefully someone can point me in the right direction.
Thanks in advance being trying to get my head around this all weekend.
Brill thanks for all the help got it sorted, for anyone who wants my solution:
$sql = "SELECT * from nav WHERE id='1'";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$i=1;
while($i<=500)
{
echo $row[$i] . "<br />";
$i++;
}

Use mysqli_result::fetch_row instead of mysqli_result::fetch_array as it will return an indexed array of values.
Example:
$result = $mysqli->query($query)
$columns = $mysqli->field_count;
while($row = $result->fetch_row()) {
for($i = 5; $i < $columns; ++$i)
echo $row[$i] . ", ";
echo "\n";
}
Edit: updated to start from column 5 as requested in comments

SELECT id AS no_title, column1 AS ... FROM table WHERE id=1
I don't see your point why you want to do this, but you can always choose an alias, I haven't tried AS " " yet, though...

Related

while ( mysqli_fetch_array() ) returns only 1 result when there are more

I just started learning PHP for an assignment I have to do for school.
I have a problem with the mysqli_fetch_array() function.
Here is my code:
//Find all book_id for a specific student_id
$query = " SELECT * FROM books_of_students WHERE student_id = '$s_id' ";
$result = mysqli_query($conn, $query);
$records_b_o_s = mysqli_num_rows($result);
If I echo the variable $records_b_o_s it correctly shows how many records MySql has returned from the table, here is a screenshot from phpMyAdmin:
books_of_students table
Here is the following part of my code:
if ($records_b_o_s >= 1) {
while ( $row = mysqli_fetch_array($result) ) {
$temp_book_id = $row['book_id'];
//do other stuff
}
}
The problem is that the loop only occurs 1 time and $row['book_id'] returns the value from the first book there is in "books_of_students" table. If for example I execute the following command inside the loop:
while ( $row = mysqli_fetch_array($result) ) {
$temp_book_id = $row['book_id'];
echo "Current book_id: " . $temp_book_id . "<br>"; //<---This one
//do other stuff
}
There will be only 1 message and it will show only the first book_id from the table
I really don't know what to do here so I will much appreciate your help! Thanks in advance :)
Thank you everybody for your time and your answers!
It turned out that I had done something stupid within the while() loop. At some point I was changing the value of the $result variable without noticing it! Now the code works as it should be!

cannot retrieve indexes correctly mysqli

$search = htmlspecialchars($_GET["s"]);
if(isset($_GET['s'])) {
// id index exists
$wordarray = explode(" ",$search);
$stringsearch = implode('%',$wordarray);
echo $stringsearch;
echo ",";
$result = mysqli_fetch_array($conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%';"));
if (!empty($result)) {
echo sizeof($result);
echo ",";
Database has 3 rows with titles test,pest,nest with corresponding id's 1,2,3. when i request domain.com/?s=est
it echos something like this
est,2,
Now when i checked $result[0] and $result[1], $result[0] echoed 1 and $result[1] didn't echo anything. When I use foreach function, it is taking only value of $result[0]
and $result should be array of all the three indexes.
I cannot find any mistake,
when i type the same command in sql console it works, somebody help me, thanks in advance.
The problem is, if you're expecting multiple rows, then don't do this:
$result = mysqli_fetch_array($conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%';"));
This only fetches the first row, you need to loop it to advance the next pointer and get the next following row set:
$result = $conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%' ");
while($row = $result->fetch_array()) {
echo $row[0] . '<br/>';
// or $row['ID'];
}
Sidenote: Consider using prepared statements instead, since mysqli already supports this.

MYSQL - Select specific value from a fetched array

I have a small problem and since I am very new to all this stuff, I was not successful on googling it, because I dont know the exact definitions for what I am looking for.
I have got a very simple database and I am getting all rows by this:
while($row = mysql_fetch_array($result)){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
Now, my question is: how do I filter the 2nd result? I thought something like this could work, but it doesnt:
$name2= $row['name'][2];
Is it even possible? Or do I have to write another mysql query (something like SELECT .. WHERE id = "2") to get the name value in the second row?
What I am trying to is following:
-get all data from the database (with the "while loop"), but than individually display certain results on my page. For instance echo("name in second row") and echo("id of first row") and so on.
If you would rather work with a full set of results instead of looping through them only once, you can put the whole result set to an array:
$row = array();
while( $row[] = mysql_fetch_array( $result ) );
Now you can access individual records using the first index, for example the name field of the second row is in $row[ 2 ][ 'name' ].
$result = mysql_query("SELECT * FROM ... WHERE 1=1");
while($row = mysql_fetch_array($result)){
/*This will loop arround all the Table*/
if($row['id'] == 2){
/*You can filtere here*/
}
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
$counter = 0;
while($row = mysql_fetch_array($result)){
$counter++;
if($counter == 2){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
}
This While loop will automatically fetch all the records from the database.If you want to get any other field then you will only need to use for this.
Depends on what you want to do. mysql_fetch_array() fetches the current row to which the resource pointer is pointing right now. This means that you don't have $row['name'][2]; at all. On each iteration of the while loop you have all the columns from your query in the $row array, you don't get all rows from the query in the array at once. If you need just this one row, then yes - add a WHERE clause to the query, don't retrieve the other rows if you don't need them. If you need all rows, but you wanna do something special when you get the second row, then you have to add a counter that checks which row you are currently working with. I.e.:
$count = 0;
while($row = mysql_fetch_array($result)){
if(++$count == 2)
{
//do stuff
}
}
Yes, ideally you have to write another sql query to filter your results. If you had :
SELECT * FROM Employes
then you can filter it with :
SELECT * FROM Employes WHERE Name="Paul";
if you want every names that start with a P, you can achieve this with :
SELECT * FROM Employes WHERE Name LIKE "P%";
The main reason to use a sql query to filter your data is that the database manager systems like MySQL/MSSQL/Oracle/etc are highly optimized and they're way faster than a server-side condition block in PHP.
If you want to be able to use 2 consecutive results in one loop, you can store the results of the first loop, and then loop through.
$initial = true;
$storedId = '';
while($row = mysql_fetch_array($result)) {
$storedId = $row['id'];
if($initial) {
$initial = false;
continue;
}
echo $storedId . $row['name'];
}
This only works for consecutive things though.Please excuse the syntax errors, i haven't programmed in PHP for a very long time...
If you always want the second row, no matter how many rows you have in the database you should modify your query thus:
SELECT * FROM theTable LIMIT 1, 1;
See: http://dev.mysql.com/doc/refman/5.5/en/select.html
I used the code from the answer and slightly modified it. Thought I would share.
$result = mysql_query( "SELECT name FROM category;", db_connect() );
$myrow = array();
while ($myrow[] = mysql_fetch_array( $result, MYSQLI_ASSOC )) {}
$num = mysql_num_rows($result);
Example usage
echo "You're viewing " . $myrow[$view_cat]['name'] . "from a total of " . $num;

How to load a selected cell from sql table PHP

sorry my code is a bit long, please bear with me. i am trying to load the link stored inside a cell from my sql table via php. The user is able to click a checkbox and choose which link to load. however, what i have is a bit off. it loads all the links present in the sql table instead of the one the user chooses. what did i do wrong? please guide. Thank you!
$sql = "SELECT * FROM previousbroadcast ORDER BY id DESC";
$result=mysql_query($sql);
$count = mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result)) {
if (isset($_POST['re_b'])){
$xml = simplexml_load_file($row['bclink']);
}
}
and the HTML is like
<input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $row['id']; ?>">
OK, a new try with the additional information you gave:
This solution is based on the following assumptions:
The value of the checkboxes you get is in some way related to a field in the database
For the sake of simplicity, I have named that field id - it can be named differently in the database, but only you would know that...
That being said:
$sql = "SELECT * FROM previousbroadcast ORDER BY id DESC";
$result=mysql_query($sql);
$count = mysql_num_rows($result);
// in this array, we now have all the values of the checkboxes the user selected
$checkboxvalues = $_REQUEST['checkbox'];
while ($row = mysql_fetch_assoc($result)) {
if (isset($_POST['re_b'])){
// if the ID of this row is mentioned in the checkboxes the user clicked
// then - and only then - load the file
if (in_array($row[id], $checkboxvalues)) {
$xml = simplexml_load_file($row['bclink']);
}
}
}
ok, your code didn't come quite well, it's incomplete.
but for what I can see the $del_record value is the checkbox array with key $i
problem there is that you are calling the database every time, so it's easy to get lost.
you should store the fetched arrays in another array and then iterate there, instead of making lots of requests to the database, that will make your code run faster and you will have more control over it.
I would get SQL to do all the filtering for you:
if (isset($_POST['re_b'])) {
$checkboxvalues = isset($_REQUEST['checkbox']) ? $_REQUEST['checkbox'] : array();
$myCheckboxes = array();
foreach ($checkboxvalues as $cbv) {
$myCheckboxes[] = mysql_real_escape_string($cbv);
}
$sql = "SELECT * FROM previousbroadcast WHERE id IN ('" . implode(",", $myCheckboxes) . "') ORDER BY id DESC";
$result=mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
$xml = simplexml_load_file($row['bclink']);
// do something here with $xml or it will get overwritten
}
}

How do I loop through a PHP array containing data returned from MySQL?

Ok I have a table with a few fields. One of the fields is username. There are many times where the username is the same, for example:
username: bob
password: bob
report: 1
username: bob
password: bob
report: 2
I did a SQL statement to select * where username='bob'; but when I do the following PHP function, it will only return the last result:
$thisrow = mysql_fetch_row($result);
I need to get every field from every row. How should I go about doing this?
$mainsection="auth"; //The name of the table
$query1="select * from auth where username='$user'";
$result = mysql_db_query($dbname, $query1) or die("Failed Query of " . $query1); //do the query
$thisrow=mysql_fetch_row($result);
echo "Study: " . $thisrow[1] . " - " . $thisrow[5];
Sorry for such a dumb question. I can't seem to get the while loops of more than one field working for the life of me.
mysql_fetch_row fetches each row one at a time. In order to retrieve multiple rows, you would use a while loop like this:
while ($row = mysql_fetch_row($result))
{
// code
}
Use a loop, and use mysql_fetch_array() instead of row:
while($row = mysql_fetch_array($result)) {
echo "Study: " . $row[1] . " - " . $row[5];
// but now with mysql_fetch_array() you can do this instead of the above
// line (substitute userID and username with actual database column names)...
echo "Study: " . $row["userID"] . " - " . $row["username"];
}
I suggest you to read this:
http://www.w3schools.com/php/php_mysql_select.asp
It will give you an overview idea of how to properly connect to mysql, gather data etc
For your question, you should use a loop:
while ($row = mysql_fetch_row($result)){//code}
As said by htw
You can also obtain a count of all rows in a table like this:
$count = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS count FROM table"));
$count = $count["count"];
You can also append a normal WHERE clause to the select above and only count rows which match a certain condition (if needed). Then you can use your count for loops:
$data = mysql_query("SELECT * WHERE username='bob'");
for ($i = 0; $i
Also, mysql_fetch_array() is usually a lot easier to use as it stores data in an associative array, so you can access data with the name of the row, rather than it's numeric index.
Edit:
There's some kind of bug or something going on where my second code block isn't showing everything once it's posted. It shows fine on the preview.
I like to separate the DB logic from the display. I generally put my results into an array that I can call within the HTML code. Purely personal preference; but here's how'd I'd approach the problem: (I'd take the $sql out of the error message in production)
<?php
$sql="
SELECT *
FROM auth
WHERE username='$user';
";
$result = mysql_query($sql)
or die("Failed Query : ".mysql_error() . $sql); //do the query
while ($ROW = mysql_fetch_array($result,MYSQL_ASSOC)) {
$USERS[] = $ROW;
}
?>
HTML CODE
<? foreach ($USERS as $USER) { ?>
Study: <?=$USER['dbFieldName'];?> - <?=$USER['dbFieldName2'];?>
<? } //foreach $USER ?>
$qry=mysql_query(select * where username='bob');
if(mysql_num_rows($qry))
{
while($row=mysql_fetch_array($qry,MSQL_NUM))
{
echo $row[0]." ".$row[1]." ".$row[2]."<br>";
}
}

Categories