mysql and php - dont know how to select and echo - php

My question is.... i have a table with 2 columns and 24 rows.
first column is only id and it goes from 1 to 24 and second column is some text in each row and follows id.
i don't know how to SELECT text from each row separated by id in first column and echo it.
I am using xampp - mysql and working in php. TY
i tried something like this and than i used variable $row to call row 0. but i think thats not right way.
$nap_query = "SELECT napomena FROM napomena";
$nap_result = mysql_query($nap_query) or die (mysql_error());
$row = mysql_fetch_row($nap_result);

You need to look at the php mysql_fetch_array documentation: http://php.net/manual/en/function.mysql-fetch-array.php
As the comments suggest mysql_fetch_row doesn't work for multiple rows.
So you can do that
while($row = mysql_fetch_array($nap_result))
echo $row['napomena'];
Aditions
It's best not to use mysql anymore and use mysqli or prefebly PDO in order to handle database connections. Read PDO and mysqli documentation here.

If you want to get only one row result
$rownum=0; //zero or something
echo mysql_result($nap_result, $rownum, "napomena");
Multi values use mysql_fetch_array
while($row=mysql_fetch_array($nap_result)){
echo $row['napomena'];
}

$nap_query = "SELECT field FROM table";
$nap_result = mysql_query($nap_query) or die (mysql_error());
while($row = mysql_fetch_row($nap_result))
echo $row['field'].'<br/>';
This will result like this
resultA
resultB
resultC
etc
Just like #punitha said, it's better to use PDO

Related

Do I Have to Use fetch_assoc() when getting MAX in a table in MySQLi [duplicate]

Looked all over. Can't find an answer. PHP docs not clear (to me).
I'm doing a simple MySQL sum through mysqli->query. How can I get the result with MySQLi like mysql_result?
It's best if you used an alias for your SUM:
SELECT SUM(`field`) as `sum` FROM `table_name`
And then, you'll be able to fetch the result normally by accessing the first result row's $row['sum'].
Whatever is given in the SELECT statement to mysqli_query is going to return a mysql_result type if the query was successful. So if you have a SELECT statement such as:
SELECT sum(field) FROM table1
you still need to fetch the row with the result, and the value of the sum() function will be the only entry in the row array:
$res = mysqli_query($dbh,'SELECT sum(field) FROM table1');
$row = mysqli_fetch_row($res);
$sum = $row[0];

PHP: How do I select from MySQL table by column position rather than by column name?

I have a table that has multiple columns, the column names can be changed in the future, and rather than my script select from the columns by their name (since that info can change), is there a way to select by column position?
For example, I want to select the second column in the table... can I do that easily?
I understand the reasons not to do this, but I still want to.
Easy solution? Just SELECT * FROM table, fetch with $row = mysql_fetch_row() and read from $row[1], it will be the content of the "second column" in order (as it starts in 0).
If you want it a little bit more professional and select only whats needed, you can get the second column name from the INFORMATION_SCHEMA using a query like this:
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'your database schema' AND TABLE_NAME = 'the wanted table name' AND ORDINAL_POSITION = 2;
But if you really want to do this the right way then know where you put your nose. If the table structure is changed and your code needs adaptations because of it, so be it. This is how it should be done. If you leave it "working" but relying in potentially wrong information it may cause much bigger problems to you later.
This is such a bad idea that I almost don't want to give you a solution, but it is possible. MySQL has a database named information_schema that stores DDL data that you can query. What you are after would be COLUMNS.ORDINAL_POSITION.
SELECT COLUMN_NAME FROM information_schema.COLUMNS
WHERE TABLE_NAME = ? AND ORDINAL_POSITION = ?
This will give you the name of the nth column, which you can use in the field list of a subsequent query. It would not make sense to do this in a single query.
The following three exampels shows you how to print the 3rd column using MySQL, MySQLi and PDO.
MySQL
while ($row = mysql_fetch_array($query)) {
print $row[2];
}
MySQLi
$sth->execute();
$sth->bind_result($var1, $var2, $var3);
while ($sth->fetch()) {
print $var3;
}
PDO
$sth->execute();
while ($row = $sth->fetchAll()) {
print $row[2];
}
In PHP you can execute query using $res = mysql_fetch_row($query). then you can fetch second column by $res[1];
I have had such problem many days ago. But I found the solution:
$conn = new mysqli("localhost", "root", "", "Mybase");
$result = $conn->query("SELECT * FROM imagesbase");
$outp = "";
while($rs = $result->fetch_array(MYSQLI_BOTH)) {`
$outp .= "Picture: ".$rs[0]." ".$rs["ImgPathName"]."";`
}
$conn->close();
echo "$outp";
This code may be changed by column number or column name. MYSQLI_BOTH , MYSQLI_NUM or MYSQLI_ASSOC are used for this.

How can I display the column names of a table using PHP?

I have been researching for days now. I always get something like this (this is what I think is the best answer):
SELECT `COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='yourdatabasename'
AND `TABLE_NAME`='yourtablename';
Yeah this one runs perfectly in SQL, but I still have no idea how I will create a PHP script to show it the same way as it does in SQL. Can anyone give me a code?
I'm really confused right now. Please help..
without PDO:
$sql = "SHOW FIELDS FROM users;";
$result_sql = mysql_query($sql) or die ("Error!\n");
while ($row = mysql_fetch_array($result_sql)) {
echo $row['Field']."<br>\n";
}
Apparently you need to retrieve data from a mysql table and then do stuff with it in php. There are several ways to do this, here is my favorite:
<?php
$query="SELECT `COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='yourdatabasename'
AND `TABLE_NAME`='yourtablename'";
$result=mysql_query($query); //This will store the whole result table in $result
$rows=array(); //Initialize array
while($row=mysql_fetch_object($result)) $rows[]=(object) $row; //Store each row of the result table in the array $rows
//Now you can access, for example, the third row and second column by saying:
echo $rows[2]->name_of_second_column
?>
Also refer to this tutorial. on how to retrieve data from a database and manipulate it afterwards.
you can do this by in mysql mysql_field_name()
Use of mysql_* is discouraged so use either pdo or mysqli
with them you can do this by
mysqli_fetch_field_direct() //for mysqli
PDOStatement::getColumnMeta() //for pdo
for example after OP comment
$sql = "SELECT * from Person";
$result = mysql_query($sql,$con);
$name = mysql_field_name($result, 0);
explanation how to use the mysql_field_name()
Syntex
mysql_field_name(data,fieldOffset)
+------------+------------------------------------------------------------------+
| data | Required. Specifies which data pointer to use. The data |
| | pointer is the result from the mysql_query() function |
+------------+------------------------------------------------------------------+
|fieldOffset |Required. Specifies which field to start returning. 0 indicates |
| |the first field |
+------------+------------------------------------------------------------------+
good read
PDO Tutorial for MySQL Developers

Echo a selected id from MySQL table

I have this
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['id'];
}
This echo's all id's found in the table.
How can I choose to echo only a selected id.
Say the second id found on the table?
EDIT
I think I have confused people and myself aswell.
Let me try to explain again.
Using the above query I can echo all results found in the table with echo $row['id'];
However I do not want echo all results, just selected ones.
You guys have suggested I use limit or a Where clause.
If I do this I will be limited to just one record. This is not what I want.
I want to echo a selection of records.
Something likes this
echo $row['id'][5], $row['id'][6], $row['id'][6]
But obviously this is incorrect syntax and will not work but hopefully you get what I am trying to do.
Thanks
If you only want the second row then you could change your query to use offset and limit e.g.
SELECT id FROM table LIMIT 1, 1
You could also use a for loop instead of the while loop and then put in a conditional.
UPDATE
Just noticed comments above - you also need to sort the PHP bug by changing mysql_fetch_array to mysql_fetch_assoc.
UPDATE 2
Ok based on your update above you are looking to get all of the rows into an array which you can then iterate over.
You can just use mysql_fetch_array and then use $array[0]. For example:
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
$ids = array();
while($row = mysql_fetch_array($result)) {
$ids[] = $row[0];
}
From what I can gather from your questions you should not be selecting all records in the table if you wish to just use the Nth value, use:
SELECT id FROM table LIMIT N, 1
That will select the Nth value that was returned. Note: The first result is 0 so if you wish to get the second value the Nth value should be 1.
mysql_data_seek() let's you jump to a specific data-set(e.g. the 2.nd)
Example:
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
//get the 2nd id(counting starts at 0)
if(mysql_data_seek($result,1))
{
$row=mysql_fetch_assoc($result);
echo $row['id'];
}
OR:
use mysqli_result::fetch_all
It returns an array instead of a resultset, so you can handle it like an array and select single items directly (requires PHP5.3)

How to use avg function?

I'm new at php and mysql stuff and i'm trying to use an avg function but i don't know how to.
I'm trying to do something like this:
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die ("Did not connect to $database");
mysql_query("AVG(column1) FROM table1 ") or die(mysql_error());
mysql_close();
echo AVG(column1);
(Q1)I'd like to see the value printed in the screen, but i'm getting nothing but an error message. How could I print this average on the screen ?
(Q2)If I had a column month in my table1, how could I print the averages by the months ?
Sorry for any bad English, and thanks for the attention.
Solution for Q1: SELECT AVG(column1) FROM table1
Solution for Q2: SELECT AVG(column1), month FROM table1 GROUP BY month
What to read?
MySQL SELECT syntax
MySQL AVG() function - there is even an example of exactly what you need
PHP mysql_fetch_assoc() function which is one of several ways to retrieve data from result set
btw: PDO is much better for database communication in PHP
Ad. 1:
$sql = 'SELECT AVG(col_name_1) AS avgColName FROM tbl_name;';
$query = mysql_query($sql);
$result = mysql_fetch_assoc($query);
var_dump($result['avgColName']);
Ad. 2:
SELECT ... FROM ... GROUP BY MONTH(date_col_name);
You need to return the result of the query into a variable which you can then use.
For example:
$query = "AVG(column1) FROM table1";
$result = mysql_query($query);
// Print out result
while($row = mysql_fetch_array($result)) {
echo $row['AVG(column1)'];
}

Categories