I'm a big noob here, so I'm trying to figure it out as a I go.
I want to take a SQL request for "id, fist and last" and store each of those in a variable.
the next half of the code would be doing things with those variable.
The lower statements are simply to see if the var is begin assigned... Apparently it is not, but I get no error, just the blank lines. How can I get the info in a set to do something with?
$newIDs = mysql_query("SELECT per_ID, per_FirstName, per_LastName FROM person_per WHERE DATE_SUB(NOW(),INTERVAL 6 MONTH)<per_FriendDate ORDER BY per_FriendDate DESC") or die(mysql_error());
while($row = mysql_fetch_assoc($newIDs)){
echo $row ['per_ID'] = $per_ID;
echo $row ['per_FirstName'] = $per_FirstName;
echo $row ['per_LastName'] = $per_LastName;
//below is for testing purposes only
echo $per_FirstName;
echo "<br/>";
}
print $per_ID;
echo $per_LastName;
I'm thinking you wanted something more like this for your test:
while ($row = mysql_fetch_assoc($newIDs)) {
$per_ID = $row['per_ID'];
$per_FirstName = $row['per_FirstName'];
$per_LastName = $row['per_LastName'];
// below is for testing purposes only
echo $per_FirstName;
echo "<br/>";
}
When you actually want to keep all the results from your query, you'll need to do something like:
$rows = array();
$i = 0;
while ($row = mysql_fetch_assoc($newIDs)) {
$rows[$i] = $row;
// below is for testing purposes only
echo $rows[$i]['per_LastName'];
echo "<br/>";
$i++;
}
Also, you should note that mysql_fetch_assoc() is actually a deprecated PHP function, according to the manual page: http://php.net/manual/en/function.mysql-fetch-assoc.php
echo $row ['per_ID'] = $per_ID;
should be
$per_ID=$row['per_ID'];
you echo of $per_ID; should then work
As its in a loop you will overwrite $per_ID each time and end up wit the last value.
It looks like your problem is in these statements:
echo $row ['per_ID'] = $per_ID;
echo $row ['per_FirstName'] = $per_FirstName;
echo $row ['per_LastName'] = $per_LastName;
The equals sign there assigns the value of variable $per_ID (which at that time is unassigned) to the array. That's not what you want.
Instead you probably want something like this:
$per_ID = $row ['per_ID'];
Things get further complicated by the fact that you have a while loop in which you would keep writing to the same three variables. So after the loop ends you would only have the value of the last set of fields.
Related
Hey I'm running php mysqli query:
<?php do { echo $row['depicao']; ?>-<?php } while ($row = mysqli_fetch_array($query)); ?>
The result I need should show the following
data-data2-data3-data4 etc.
However what I'm seeing is:
-data-data2-data3-data4
how can I get the "-" to not appear as the first result?
Ive tried this but I get the same result.
<?php do { echo $row['depicao']; echo'-'; ?><?php } while ($row = mysqli_fetch_array($query)); ?>
Thanks
In
do { echo $row['depicao']; ?>-<?php }
while ($row = mysqli_fetch_array($query))
$row gets defined after first iteration, and not before. That's why
$row['depicao'] outputs nothing. If you had error_reporting on - you would also see a notice.
So, first fix is to define $row first and then output it:
while ($row = mysqli_fetch_array($query)) {
echo $row['depicao'];
echo '-';
}
But in this case your output will be ended with -.
So, one of the solutions is to collect values in array and implode'em:
$values = [];
while ($row = mysqli_fetch_array($query)) {
$values[] = $row['depicao'];
}
echo implode('-', $values);
Use while loop instead of do...while
Because when you use do while loop it'll execute once always and then it'll check the condition and that's why you got the - at very first of your result.
So use while loop to check the condition, if true then code under loop will execute otherwise not.
I'll strictly recommend you to learn about loops.
Try using while loop instead of do-while.
<?php while($row = mysqli_fetch_array($query)) { echo $row['depicao'];echo'-';} ?>
The problem with do while is that it executes at least once even if the condition fails. Hence one "-" is printed in beginning even without evaluating the condition.
If the goal is just to remove the extra "-" then it can be done with-
<?php do { echo $row['depicao']; if($row['depicao']!=null) echo "-"; } while ($row = mysqli_fetch_array($query)); ?>
Some code to fetch the field names by connecting it with db:
<?php
#mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$result = mysql_query("SELECT * FROM sample");
$storeArray = Array();
while ($row = mysql_fetch_array($result)) {
if (mysql_num_rows($result) > 0) {
$storeArray = $row['name'];
echo $storeArray;
}
}
?>
The above code works just fine but when it runs it gives me ramuraja. Here ramu and raja are seperate fields. But its giving me a joined output.
How can i get the two field value seperately like ramu and raja.
You print / echo the values directly after one another. Using echo $storeArray.'<br>'; would print a linebreak additionally, thus printing
ramu
Raja
However, you could also store all the variables in an array, for example with $storeArray[] = $row['name']; instead of $storeArray = $row['name'];. That would create a new array element, the value being $row['name'], while the key is incrementing for every element being added.
After having received all rows that match the query, you could loop through the array and Display the answers.
EDIT: Please check out mysqli or PDO; those PHP extensions are standard with newer versions and should be used instead of the old (and now deprecated) mysqli solution. Don't worry, they can do the same (and much more).
You need to do a for each statement to iterate through the array and echo the field along with a line break
First of all, you're declaring $storeArray as an array in this line: $storeArray = Array();, but later you replace it with a string $storeArray = $row['name'];
If you want to use $storeArray as an array, change this line:
$storeArray = $row['name'];
into
$storeArray[] = $row['name']; //add element to the array
Now loop all the results (remove echo $storeArray;)
After you've fetched all the results you kan echo them like:
foreach($storeArray as $name){
echo $name.'<br>';
}
Some confusion in code ....
first check ifthere are results:
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
....
}
}
than be more clear about what you wont:
an array :
$storeArray = Array();
or a string:
$storeArray = $row['name'];
I would so like this:
$storeArray = Array();
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$storeArray[] = $row['name'];
}
}
// array
print_r($storeArray);
// string
echo implode(',', $storeArray);
Am making a really simple php page which pulls data from a really simple database and displays it as charts for a wall monitor.
I've got the data from the db, no problem, but I seem to be struggling splitting that data up
For now i'm just echoing the data to make sure i have what i need.
My code looks like this:
<?php
mysql_connect("host", "user", 'password' or die(mysql_error());
mysql_select_db("databax") or die(mysql_error());
$dbdata = mysql_query("SELECT * FROM dbcpman_resources")
or die(mysql_error());
$column = mysql_fetch_array( $dbdata );
echo $column[0]."<br>";
echo $column[1]."<br>";
echo $column[2]."<br>";
echo $column[3]."<br>";
echo $column[4]."<br>";
echo $column[5]."<br>";
?>
Indeed, it works - it will echo data from the database, but as i've not specified the row anywhere, its just giving me the first row.
I need to be able to work with each row seperately.
There will only ever be 6 rows in this table.
So can anyone help me out with how I go about replicating this for rows 2,3,4,5 and 6?
Thanks in advance!! :)
You need to loop over the result set. The easiest way is to use a while loop as this automatically terminates at the end of the result set, like this.
while ( $row = mysql_fetch_array( $dbdata );
echo $row [0]."<br>";
echo $row [1]."<br>";
echo $row [2]."<br>";
echo $row [3]."<br>";
echo $row [4]."<br>";
echo $row [5]."<br>";
}
Also if you were to change the function that returns the resuilts to use mysql_fetch_assoc() you can reference each field with the name it has on the database so the code is easier to read, like this:
I dont know your field names so I made some up.
while ( $row = mysql_fetch_array( $dbdata );
echo $row ['name']."<br>";
echo $row ['date']."<br>";
echo $row ['time']."<br>";
echo $row ['value1']."<br>";
echo $row ['value2']."<br>";
echo $row ['value3']."<br>";
}
First of all, I'd rather use mysql_fetch_assoc() instead of mysql_fetch_array() since it doesn't srew up your result, if the table structure changes.
It would be even better if you used either mysqli or PDO instead of mysql_* functions, since they are marked deprecated already!
Second please note, that either function just fetches ONE record from your resultset at a time. To fetch all records try the following:
$records = array();
while($row = mysql_fetch_assoc($dbdata)) {
$records[] = $row;
}
You can do a print_r($records); to see what's inside $records after fetching all.
put this line $column = mysql_fetch_array( $dbdata ); in while loop like this
while($column = mysql_fetch_array( $dbdata ))
{
echo $column[0]."<br>";
echo $column[1]."<br>";
echo $column[2]."<br>";
echo $column[3]."<br>";
echo $column[4]."<br>";
echo $column[5]."<br>";
}
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;
In a Flex project, I have an array with objects in it. I want to save this array in a cell on a mysql table along with some other basic info like title, and an id.
EDIT: just clarifying since i seem to be getting responses explaining how to echo all the rows... I'm trying to echo the contents of an array that was serialized and placed in a single cell. This array has objects in it.
So, I have this code here to serialize the array, and insert it along with the other info into my DB:
function submitLogDbObj($array,$id,$title)
{
$title=mysql_real_escape_string($title);
return mysql_query("INSERT INTO logs (text,id,title) VALUES ('".serialize($array)."','$id','$title')");
}
Then for a test i'm trying to make a loop that will display the log in a way that looks like a conversation...
an object in my array would look something like:
[1]
icon = ""
msg = "this is a test"
name = "Them: "
systemMsg = 0
[2]
icon = ""
msg = "yep it sure is"
name = "You: "
systemMsg = 0
So here's what i've got so far, but its not working! How can I make a loop that will take that array from the DB, unserialize it and then echo the convo in a way that looks like a chat log?
Thanks!
<?php
include_once("dbinfo.php");
$id= $_GET['id'];
$result = mysql_query("SELECT text,title FROM logs WHERE id='$id'")
or die(mysql_error());
$row = mysql_fetch_array($result);
if($result)
{
$log = unserialize($row['text']);
echo 'starting loop!';
echo "<ul>";
/* im not sure how to represent the length of an array in php thats why i just have $log.length */
for ($i = 1; $i <=$log.length; $i++)
{
echo "<div id='logbox'>";
echo "<li>";
$name=$log[$i]['name'];
$msg=$log[$i]['msg'];
echo "$name - $msg";
echo "</li>";
echo "</div>";
echo "<br />";
}
echo "</ul>";
echo 'finished loop!';
}
else
{
echo "Looks like this chat log has been deleted. Sorry!";
}
Well, there're a few things which could be better here:
The length of an array is found through count( $array ) or sizeof( $array )
$value . $otherValue means concatenate those two values. Since length is undefined in this context, $log.length means "$log.length".
The best way to loop through an array is foreach( $set as $val) or foreach( $set as $key => $val )
The preferred method of iterating through a SQL result is the while loop: while($row = mysql_fetch_array($result)){ or do... while (see below). Unless you specifically and consciously only want one, then it would be best to use that. And if you do only want one, then put a Limit in the query.
Serialized arrays in databases has a redundant flavor. Are you sure that this is what you want?
Your serialized array, before it is inserted, should also be run through mysql_real_escape_string.
br really shouldn't be needed if you're surrounding something in its own div.
Indent properly or the kitten of death will come for you.
The improved code:
$row = mysql_fetch_array($result);
// row could be empty if there were no results
if($row)
{
// we've already grabbed the first value, so we need
// to invert while into do... while.
do
{
$log = unserialize($row['text']);
echo "<ul>";
foreach( $log as $line )
{
// Are you sure this should be outside of the li?
echo "<div id='logbox'>";
echo "<li>";
$name=$line['name'];
$msg=$line['msg'];
echo "$name - $msg";
echo "</li>";
echo "</div>";
}
echo "</ul>";
}
while( $row = mysql_fetch_array($result) );
echo 'finished loop!';
}
else
{
echo "Looks like this chat log has been deleted. Sorry!";
}
Firstly, get into the habit of indenting your code properly, it will save you a lot of frustration when looking for errors.
You don't need to know the length of the array, you can just use a while loop: (coding from the hip here so let me know if you get errors)
$result = mysql_query("......") or die("Query failed");
//Keep going while $row isn't FALSE
//mysql_fetch_array returns false when there are no more rows
while($row = mysql_fetch_array($result)){
//You can close PHP tags here and insert the
//variables in the HTML, it often looks neater
//and your editor can colour code HTML, helping
//you to find problems
?>
<div>
<li><?php echo $row['name'] ?></li>
<li><?php echo $row['msg'] ?></li>
</div>
<?php
}
See the "fetch array while loop" of this tutorial for more examples.
$result = mysql_query("SELECT text,title FROM logs WHERE id='$id'")
echo "<ul>";
while ($row = mysql_fetch_assoc($results)) {
$name = $row['name'];
$msg = $row['msg'];
//display data how ever you want
}
echo "</ul>";