Fetching one row in database - php

<?php
$stmt = $conn->prepare('SELECT Distinct(specificcategoryname) FROM `clientstable` c,specificcategories s where c.PhoneNumber=:phNo and c.SpecificCategoryId=s.SpecificCategoryId');
$stmt->execute(['phNo'=>$phNo]);
while($row = $stmt->fetch()) {
echo "<tr>";
echo "<td>".$row['specificcategoryname']."</td>";
echo "</tr>";
}
?>
I have code like this need to fetch only one specific value from the database. how can i get the preferred value?

Your, where clause is matching with more than one records that's why more than one records are fetching. if you want to select specific single record then there should be change in sql query. I can't more help because, i need to see the complete schemas of both tables ( clientstable and categorytable) that you are using. Thank you

Related

Show each row colums information php and sql

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();

save pdo query result to variable and use it on other queries

I'm new in php programming, please help me.
I've to make two postgres queries from two separate databases, but one of the fist queries condition based on the other query result:
1st query:
<?php
$result = "SELECT ...
WHERE ... ";
$query = $pgszlaConn->prepare($result);
$query->execute();
while($row = $query->fetch(PDO::FETCH_BOTH)) {
$contractid=$row[0];
echo "<tr><td>$contractid</td></tr>";
?>
/In this query I've multiple results./
2nd query:
<?php
$result = "SELECT ...
WHERE contract.contract_id= :contract";
$query = $pgConn->prepare($result);
$query->bindparam(':contract', $contractid);
$query->execute();
while($row = $query->fetch(PDO::FETCH_BOTH)) {
echo "<tr><td>$row[0]</td></tr>";
?>
My problem is that the 2nd query has only one result based on the 1st query multiple results.
I'm not sure is this a good solution or not but my programming skills not so advanced ;-)
Please help me if you can!
Thanks a lot!
D. Attila
If i understand what you mean.
You need to make the second query within the loop of the first query so that for each id of the first query available, the id will be passed to the second query to query the database of the second table.
Not with my system would have shown you some of my code.
while($row = $query->fetch(PDO::FETCH_BOTH)) {
echo "<tr><td>$contractid</td></tr>";
## now you make the second query to the second table with the id of the first table
$result = "SELECT WHERE contract.contract_id= :contract";
while($row = $query->fetch(PDO::FETCH_BOTH)) {
echo "<tr><td>$row[0]</td></tr>";
} ## end of second query loop
} ## end of first query loop
Something like this should work just get the idea and implement it for yourself

Mysql php Update doesnt work in while loop

I am new in programming and I came across issue with Mysql Update code. I have 4 different row values in '100m' Column and I am trying to use While loop to calculate $points1 for each different value of row, then afther calculatin, update table with it depending on row value. But from all 4 row just 3rd one gets Total_score update.
Table:
Table Structure:
Code:
<?php
include ("config.php");
$sql= "SELECT * FROM data_from_file";
$result= $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
$P=$row['100m'];
$A=25.4347;
$B=18;
$C=1.81;
$points1 = $A*(($B-$P)**$C);
$insert =$db->query("UPDATE data_from_file SET Total_score=$points1 WHERE 100m=$P");
echo $P;
echo "<br>";
echo $points1;
echo "<br>";
};
}
?>
Why just 3rd one is updating?
You shouldn't use names that begin with numbers on your table columns.
$insert =$db->query("UPDATE data_from_file SET Total_score=$points1 WHERE `100m`=$P");
Try this
Use single quotes for variables
$insert =$db->query("UPDATE `data_from_file` SET `Total_score`='$points1' WHERE `100m`='$P'");
Using WHERE 100m=$P is bad idea, because it updates all rows where value of 100m equals $P. You should use WHERE id=$row['id'], so you will be sure that only one row will be updated.
Can you post a table structure? I want to know columns types.

Allow user to select specific row of sql select results?

Not sure if this is even possible so sorry if this is a stupid question. I have a sql select query that I will post below. It displays 5 fields into a table from my orders database table. Is there any way that a user can click on one of the rows and then that would take them to a new page showing only that rows results? Is it somehow possible to store the select query results into a session for me to call on the next page? I would like them to be able to print invoices this way. Here is the select sql code.
$sql = "SELECT id, login_id, companyname, address, cost FROM orders WHERE `login_id` = '$_SESSION[login]'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>id</th><th>login_id</th><th>companyname</th>tr><th>address</th><th>cost</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["login_id"]."</td><td>".$row["companyname"]."</td><td>".$row["address"]."</td><td>".$row["cost"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
Simply save the value of first column (ID). Then use it for new query which selects only this row.
Expanding on i486's answer, here is how you can achieve it in more detail:
Since you already have the $row["id"], you can use this to generate a link:
echo "<a href='newpage.php?id=".$row["id"]."'>Click here</a>";
Now in newpage.php:
// You can access parameters in the url using GET
$id = $_GET["id"];
// Now you can build a new SQL query using this $id, and echo the results table
Do look up the following things:
REST: This explains how GET and POST works
Prepared SQL statements: This will prevent SQL injection, and is needed when you are working with GET or POST values in an SQL query (otherwhise malicious users can destroy your database!)

MySQL while loop query inside other while loop query

<?php
include 'config.php';
$conn = mysql_connect("$hostname", "$username", "$password") or die ("Failed to connect to DB.");
mysql_select_db("$dbname",$conn);
$sql="SELECT * FROM opdrachten";
$result=mysql_query($sql,$conn);
while ($row= mysql_fetch_array($result))
{
echo $row['name'];
echo "<br>";
$opdrachtid = $row["id"];
$sql2="SELECT * FROM resultaten WHERE(opdrachtid='".$opdrachtid."')";
$result2=mysql_query($sql2,$conn);
while ($row2= mysql_fetch_array($result2))
{
echo "
<li>
<a href=\"result.php?id=".$row2["id"]."\">
<img src=\"".$row2["img"]." \"width=\"150\" height=\"150\">
<div><span>TEXT HERE</span></div>
</a>
</li>";
}
}
?>
What I want my code to do is (in a loop):
Fetch all rows from the table 'opdrachten' and echo their 'name'.
Grab the 'id' from each of the rows in 'opdrachten' > store in variable $opdrachtid
Fetch rows from table 'resultaten' where 'opdrachtid == $opdrachtid' (which I just stored)
Echo the 'id' and 'img' from the rows fetched from 3.
What I want to see on my page:
The name of the 'opdrachten' (objective) in table 'opdrachten'
with directly underneath
The images (the url's of which are stored in table 'resultaten')that are assigned to these objectives (WHERE opdrachten.id = resultaten.opdrachtid)
I've looked into JOIN since that's the answer to most of the related topic's I've read here, but that doesn't seem to be what I'm looking for since I'm echo'ing in the first while and declare variables that are used for the second query.
Tables used:
'resultaten'
id | opdrachtid | name
'opdrachten'
id | name
Again, resultaten.opdrachtid == opdrachten.id
Thanks in advance, appreciate the help :)
I would certainly suggest using a JOIN here that way you can get all this data in one go. I will add one caveat however - this would take more memory that querying the database in a loop like you are currently doing, so if you have a large number of rows in either table, this might not be a suitable approach.
The query would simply be:
SELECT * FROM opdrachen
INNER JOIN resultaten ON opdrachen.id = resultaten.opdrachenid
You can then set up an array that is keyed on each id very simply like this:
$array = array();
while ($row = mysql_fetch_array($result)) {
$array[$row['id']][] = $row;
}
This give you an easy way to iterate through the results, one id at a time like this:
foreach ($array as $id => $rows_for_id) {
// output stuff for row group
foreach ($rows_for_id as $resultaten_row) {
// output stuff for resultaten rows
}
}
A few other suggestions:
Don't use mysql_* functions as they are deprecated. Learn how to use mysqli or PDO.
Don't use SELECT * queries. Its is lazy and wastes bandwidth, transfer time, and system memory. Only query for the specific fields you are actually interested in. So replace the * in my example with the actual field you need.
SELECT opdrachten.*, resultaten.* FROM opdrachten
INNER JOIN resultaten
ON resultaten.opdrachtid = opdrachten.id;
just use this as the original sql statement and iterate over it.

Categories