Show each row colums information php and sql - php

I want to print the values of custom columns for all rows, I've got a sql developer file, i mean that i want to print some columns of every rows, if for example my table is named client and has name, subname and email i want to print every client name, subname and email I've found how to make it with mysql but I want to make it with php and sql developer.
The code I've shown only shows the first user name and not the rest names and other columns of other users.
<?php
function clientes($conexion) {
$consulta = "SELECT NOMBRE FROM CLIENTE";
$stmt = $conexion -> prepare($consulta);
$stmt -> execute();
return $stmt -> fetchColumn();
}
echo clientes($conexion);
?>

You're only getting one column since you're explicitly only ask for one column (by using fetchColumn()) and the fact that you've only told SQL to return one single column.
Change your query:
// Replace column1 etc to the real column names
SELECT column1, column2, column3 FROM CLIENTE
Then instead of using fetchColumn() (which is for fetching one column), use:
return $stmt->fetchAll(PDO::FETCH_ASSOC);
and you should get an array containing associative arrays (one per row) with all three columns.
However, you have another issue:
echo clientes($conexion);
Since you're now returning an array, you can't just echo it straight off. If you do, you will get a warning about "Array to string conversion". You need to iterate through the array and output the data as you want it:
$data = clientes($conexion);
// Again, change the column names
foreach ($data as $row) {
echo $row['column1'];
echo $row['column2'];
echo $row['column3'];
}
This will output all the data. You get to decide on the layout though.

I want to print every client name, subname and email i've found
Then you should use fetchall() this will fetch all the results as an array then iterate through the array and print each element of the array
function clientes($conexion) {
$stmt = $conexion ->query("SELECT name,subname,email FROM CLIENTE")->fetchall();
foreach($stmt as $row){
echo "Client Name : ".$row['name']."<br>";
echo "Client subname : ".$row['subname']."<br>";
echo "Client email : ".$row['email']."<br>";
}
}
clientes($conexion);
?>

For getting all columns
You need to address your SQL Query different for it to work probably. At the moment you are only looking for the field nombre. Try to change it to:
$consulta = "SELECT * FROM CLIENTE";
With the asterisk you calling all fields in the table cliente. For performance you should only call the fields your are needing. This would look like this:
$consulta = "SELECT nombre,dni,sexo FROM CLIENTE";
For getting all rows
At the moment you just address one row here. You need to change your code to
return $stmt ->fetchAll();

Related

passing parameter to select statement from url

I have a database with a table which has two columns, lets say aa_id and bb_id - each of the the columns is a foreign key relating to another table and both columns are making a composite key for this particular table. there are several rows containing either the same aa_id and different bb_id or the same bb_id and different aa_id.
using pdo I want to extract the rows of the same - let's say - aa_id and I want to do this passing the parameter value in url. so the result of the select statement should be several rows and they should be saved as - for example - an array.
I have tried to do this with following code:
$sql = sprintf("select aa_id, bb_id from a_table where aa_id=:aa_id");
$res = $db->query($sql);
$rows = $res->fetch(PDO::FETCH_ASSOC);
foreach($rows as $key=>$value)
{
echo $key . " - " . $value . "</br>";
}
And it give no result.
I does work if I state the value of aa_id in the query like this
$sql = sprintf("select aa_id, bb_id from a_table where aa_id=191919");
, but it extracts no data if I put the value in url.
I am not really sure what to search for in the web because I don't know what's the notation called (if it is). If somebody could tell me what may be wrong with the code or give me directions to what I should look for in the web among tutorials or documentation I will be grateful. Perhaps somebody could recommend a good source of knowledge about mysql, php and pdo... Thanks in advance.
Well yeah, :indicator doesn't just automatically load in $_GET['indicator'], you need to manually bind it.
Assuming the URL ends with, ?aa_id=191919, your code might look something like this:
$sql = "select aa_id, bb_id from a_table where aa_id=:aa_id";
$res = $db->prepare($sql);
$res->bindValue(':aa_id', $_GET['aa_id'], PDO::PARAM_INT);
$res->execute();
$rows = $res->fetch(PDO::FETCH_ASSOC);
while($row=$res->fetch(PDO::FETCH_ASSOC))
{
print_r($row);
}

Add link to mysql row result which points to the same result

Hello my data base have various columns , in a mysql fetch I am listing only the title column, but I would like that list to make a link on the already listd result which link will open a new page with the same result but this time listing all the columns from the table on this row.
mt SQL fethc is:
(!$result = mysqli_query($con,"SELECT * FROM tablename WHERE type = 'Panes'"))
and my sql result is: <?php echo $row['name']; ?> -> which result I would like to be link.
I wold like to know if somebody have any suggestion for a possible resolution. Thanks!
You cannot do that if you want to have a single query in your code(base from your query).
You must do another query for the click item or link..
If you do not need all the columns in your table to not use * instead select only what you need to make your code more readable and to be faster to execute.
Revised your string query,
"SELECT id, name FROM tablename WHERE type = 'Panes'"
and in your code to display the result to make a link,
<?php echo $row['name']; ?>
And in your page displayAllColumns.php you must get the passed data through get method
$id = $_POST['id'];
//then make a query for that to select all the data on that id
//just have to type only the string so
"SELECT * FROM tablename WHERE id = '$id'"
//you must use `*` because you need to display all the columns then write your table code to display the result.
Hope it helps
Try echoing an anchor tag. $row['name']
Use something like this:
<?php echo $row['name']; ?>
The display_item.php script then displays the row with the ID in $_GET['id'].

MYSQL Statement with Array Variable

So I have the following mysql statement saving to an array:
$sql = "SELECT did FROM did WHERE id = '$did_id'";
$result = mysqli_query($link, $sql, MYSQLI_STORE_RESULT);
while($row = $result->fetch_row()){
$did[] = $row;
}
That part works great. But now I need to take the values in the $did array and perform another lookup using the values in it. The way it works is we have users assigned to certain did's. So I find the did's that the user is assigned to (the $did array) and only show them results from another table based on those did values. I have no idea how this part works, but this is what my next statement needs to do:
SELECT * FROM log WHERE did_id = "the values in $did array"
Hope someone can help. I really appreciate it. I haven't really been able to find anything on it.
You can use php's join with mysql's IN to make comma separated strings you can also use implode , join() is an alias of implode();
SELECT * FROM log WHERE did_id IN( ".join(',',$did).")
One thing to mention here that your $did should contains ids in manner like
array("1","2","3"....)
So in your loop fetch first index that holds did column value
$did[] = $row[0];
Note: i assume did , did_id type is int or bigint

How to query all fields in a row

I know this is very simple, but I haven't used PHP/MySQL in a while and I have been reading other threads/php website and can't seem to get it.
How can I query a single row from a MySQL Table and print out all of the fields that have data in them? I need to exclude the NULL fields, and only add those that have data to an html list.
To clarify, I would like to display the field data without specifying the field names, just for the reason that I have a lot of fields and will not know which ones will be NULL or not.
What you've outlined requires 4 basic steps:
Connect to the database.
Query for a specific row.
Remove the null values from the result.
Create the html.
Step 1 is quite environment specific, so that we can safely skip here.
Step 2 - SQL
SELECT * from <tablename> WHERE <condition isolating single row>
Step 3 - PHP (assuming that $query represents the executed db query)
//convert the result to an array
$result_array = mysql_fetch_array($query);
//remove null values from the result array
$result_array = array_filter($result_array, 'strlen');
Step 4 - PHP
foreach ($result_array as $key => $value)
{
echo $value \n;
}
Just SELECT * FROM table_name WHERE.... will do the trick.
To grab data from specific fields, it would be SELECT field_1,field_2,field_3....
you have to make a string which represent mysql query. Then there is function in php named mysql_query(). Call this function with above string as parameter. It will return you all results. Here are some examples
You need to do it like this...
First connect to your sql... Reference
Now make a query and assign it to a variable...
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename");
If you want to retrieve a single row use LIMIT 1
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename LIMIT 1");
If you want to fetch all the columns just use * instead of column names and if you want to leave some rows where specific column data is blank you can do it like this
$query = mysqli_query($connect, "SELECT * FROM tablename WHERE column_name4 !=''");
Now fetch the array out of it and loop through the array like this..
while($show_rows = mysqli_fetch_array($query)) {
echo $show_rows['column_name1'];
echo $show_rows['column_name2'];
}
If you don't want to include the column names in the while loop, you could do this:
while($show_rows = mysqli_fetch_array($query)) {
foreach( $show_rows as $key => $val )
{
echo $show_rows[$key];
}
}

mySQL fetch column based on another column in PHP

I'm trying to write my first PHP script with mySQL and I desperately need some help. I'm sure this is relatively simple, but if I have one field in my table (username, for example), and I want to fetch another field (name, for example), that is in the same row as the given username, how do I do that?
Again, I'm sure this is easy, but I'm lost, so I'd really appreciate any help. Thanks!
$sql = "SELECT username, name FROM table";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
echo "This {$row['username']} has the name {$row['name']}\n";
}
halfdan's answer sort of works, but it fetches all rows and displays them. What you want is a WHERE clause, which lets you filter the contents of the table so the query only returns the row(s) you want:
SELECT username, name
FROM sometable
WHERE (username = 'johndoe');
This will return only the rows where the username field is equal to 'johndoe'. Conceptually, it's equivalent to:
$results = mysql_query("SELECT username, name FROM table");
while($row = mysql_fetch_assoc($results)) {
if ($row['username'] == 'johndoe') {
// do something, this is a row you want
} else {
// not a row you want. ignore it, or deal with it some other way
}
}
the main difference is that for large data sets in the database, doing client-side filtering like this is expensive, as the entire contents of the table has to be transferred over. Using a WHERE clause to limit things to just what you want is far more efficient in the long run.

Categories