I'm trying to make a query that then displays certain results based on previous queries
The idea is that when someone logs into the page, it gets the session username and and saves it to a variable, from there the first query selects a row based on the session username, gets that value and does the same in the second query but on a different table this time getting the row based on the result from query 1 and query 3 is same as two and then its meant to echo it out
here's the code
$con = mysqli_connect("localhost","root","","boats4u");
$search = $_SESSION['myusername'];
if(mysqli_connect_errno())
{
echo "Failed to connect to database". mysqli_connect_error();
}
$pre_res = mysqli_query($con,"SELECT ownerNo FROM boatowner WHERE email ='$search'");
$pre_res = $pre_res -> fetch_assoc();
$result = mysqli_query($con,"SELECT boatNo FROM boatforrent WHERE ownerNo ='$pre_res'");
$result = $result -> fetch_assoc();
$result2 = mysqli_query($con,"SELECT * FROM boatviewing WHERE boatNo = '$result'");
echo "<table border='1'>
<tr>
<th>Client No</th>
<th>Boat No</th>
<th>View Date</th>
<th>Comments</th>
</tr>";
while ($row = mysqli_fetch_array($result2))
{
echo "<tr>";
echo "<td>". $row['clientNo']."</td>";
echo "<td>". $row['boatNo']."</td>";
echo "<td>". $row['viewDate']."</td>";
echo "<td>". $row['comment']."</td>";
}
echo "</table>";
?>
this is what displays
Notice: Array to string conversion in
E:\Download\Xampp\htdocs\owner.php on line 29
If I remove the first query then it no errors but obviously the search doesn't work then
any help appreciated
You should do one query and also parametize the search parameter. Something along the lines like:
$stmt = $con->prepare('
SELECT boatviewing.*
FROM boatowner owner
LEFT JOIN boatforrent ON boatforrent.ownerNo = owner.ownerNo
LEFT JOIN boatviewing ON boatviewing.boatNo = boatforrent.boatNo
WHERE owner.email = ?
');
$stmt->bind_param("s", $search);
$stmt->execute();
$result = $stmt->get_result();
Such code is normally more robust against SQL injection and it's also easier in case you change your database layout.
Next to that you actually run one query instead of three which allows the database to optimize data-retrieval and keeps roundtrips between the PHP script and the database server low.
Related
Could anyone help me fetch data from a database and view it in a table? I am new to codeigniter framework.
here is a short Code for fetching Data from an SQL-Table
First you create a Connection:
// Create connection
$db = mysqli_connect($host,$username,$password,$database)
or die('Error connecting to MySQL server.');
The Values:
$host = your host-ip or URL or localhost
$username = Your Database Username
$password = your Database Password
$database = your database's Name
Then you need to request(query) something from a Table in that Database
For Example like this:
$sql = "SELECT * FROM $table ORDER BY id DESC";
$res = mysqli_query($db, $sql) or die("Fehler:$sql");
while($row = mysqli_fetch_assoc($res))
{
}
Now this Code will get all the Data out of a Table and orders it by the ID Descending.
In that code $table stands for your Table-Name and $db is your Database Name, as PHP7 needs it by every Query.
The Results eg. ALL Data in the Table, ordered by ID is now stored in the single Variable $res. If you want you can use code to check 'if ($res = true)' in order to make sure that you actually get a result from the query and catch an exception.
The 'Method mysqli_fetch_assoc()' will now give you all the Data nice and easy.
All you have to do is use this While Loop like this:
while($row = mysqli_fetch_assoc($res))
{
$username = $row['username'];
$date= $row['date'];
}
Meaning, that every While Cycle goes through one Row of results in the order you chose to query it at.
And $row acts as an Array where the Idice, ([] text in these brackets) corresponds to the given Clumn Name in your Table
Hope i could help you out :)
And please in the future state your question a little more clear and detailed and show that you have actually worked on your Problem before asking
Spytrycer
Edit
I overread the table part :)
In order to view it in a Table you should do something like this:
echo"<table border = '1'>";
echo"<tr>";
//Do <td> and </td> for as many Columns as you have and write them between the td's
echo"<td>";
echo"Column Name";
echo"</td>";
//Then comes the Data part
$sql = "SELECT * FROM $table ORDER BY id DESC";
$res = mysqli_query($db, $sql) or die("Fehler:$sql");
while($row = mysqli_fetch_assoc($res))
{
//open new Row
echo"<tr>";
//Do this td, data, /td loop for as many Columns you have in your
Database. For a Database with id, username and Password for example:
echo"<td>";
echo"$row['id']";
echo"</td>";
echo"<td>";
echo"$row['username']";
echo"</td>";
echo"<td>";
echo"$row['password']";
echo"</td>";
echo"</tr>";
//Close row
}
<?php
if(isset($_POST['submitted'])){
//Connecting to the database
include('includes/connection.php');
// Creating variables to Post selected input item into database
$meeting_type = explode('|', $_POST['meeting_type']);
$date_picker = $_POST['date_picker'];
//$query = "SELECT * FROM meeting_tb WHERE meeting_type = '$meeting_type[1]'";
$query = "SELECT meeting_id, meeting_type, date FROM meeting_tb WHERE date in (select Max(date) as mindate from meeting_tb where meeting_type = '$meeting_type[1]')";
$query_result = mysqli_query($db_con, $query) or die("error retrieving data");
$row_meeting = mysqli_fetch_array($query_result, MYSQLI_ASSOC) or die("Not able to retrieve information");
$query_item = "SELECT join_tb.item_id, item_name, item_description FROM join_tb INNER JOIN meeting_item_tb ON join_tb.item_id = meeting_item_tb.item_id WHERE join_tb.meeting_id = '$row_meeting[meeting_id]'";
$result = mysqli_query($db_con, $query_item) or die("error retrieving data");
echo "<table>";
echo "<tr> <th>ITEM ID</th> <th>ITEM NAME</th> <th>ITEM DESCRIPTION</th> </tr>";
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<tr><td>";
echo $row['item_id'];
echo "</td><td>";
echo $row['item_name'];
echo "</td><td>";
echo $row['item_description'];
echo "</td></tr>";
}
echo "</table>";
}
//End of IF statement
?>
The Issue involves the use of $row_meeting[meeting_id] in the second select statement. If I put a numeric value in place of $row_meeting[meeting_id], the select statement works and it displays an output on the browser. But if I use $row_meeting[meeting_id] in the second select statement, it does not get the data from the database
By putting single inverted commas around $row_meeting[meeting_id], you are converting the number to a string when parsing it to SQL. To avoid parsing it to as string you can simply remove the single inverted commas. So your select statement will look like:
$query_item = "SELECT join_tb.item_id, item_name, item_description FROM join_tb INNER JOIN meeting_item_tb ON join_tb.item_id = meeting_item_tb.item_id WHERE join_tb.meeting_id = $row_meeting['meeting_id']";
Hope this helps.
Try this in your second query
$query_item = "SELECT join_tb.item_id, item_name, item_description FROM join_tb INNER JOIN meeting_item_tb ON join_tb.item_id = meeting_item_tb.item_id WHERE join_tb.meeting_id = ".$row_meeting[meeting_id].";";
It is possible because of the single quoted around the variable.
$sql="SELECT userId FROM eventmember WHERE eventid='$event_id';";`
$resultset = mysql_query($sql);
$row = mysql_fetch_array($resultset);
I got specific userid from specific event column like eventid==> eid-01(us-0, us-3,...),
$num_row = mysql_num_rows($resultset);
while($row) {
for($i = 0; $i<$num_row; $i++) {
$sql = "SELECT userId, firstName FROM userinfo WHERE userId='$row[$i]';";
$resultset = mysql_query($sql);
$row22 = mysql_fetch_array($resultset);
$us_id = $row22['userId'];
$us_name = $row22['firstName'];
echo "<tr>";
echo "<td>ID:</td> <td class='text2' align='center' colspan='2'>
<b> $us_id </b>
</u></td>";
echo "</tr>";
break;
}
$row = mysql_fetch_array($resultset);
}
On that code I got only one userid info but there is more userid against one event.
First of all, use if statement to check whether the returned result set contains any row or not, like this:
if($num_row){
// your code
}
Second, use a while loop to loop through the result set and display it's contents, like this:
while($row22 = mysql_fetch_array($resultset)){
// your code
}
And finally, please don't use mysql_ database extensions, they were deprecated in PHP 5.5.0 and were removed in PHP 7.0.0. Use mysqli or PDO extensions instead. And this is why you shouldn't use mysql_ functions.
So your code should be like this:
<?php
$sql="SELECT userId FROM eventmember WHERE eventid='$event_id'";
$resultset = mysql_query($sql);
$row = mysql_fetch_array($resultset);
$num_row = mysql_num_rows($resultset);
if($num_row){
$sql = "SELECT userId, firstName FROM userinfo WHERE userId='" . $row['userId'] . "'";
$resultset = mysql_query($sql);
?>
<table>
<tr>
<td>User ID</td>
<td>First Name</td>
</tr>
<?php
while($row22 = mysql_fetch_array($resultset)){
echo "<tr><td>{$row22['userId']}</td><td>{$row22['firstName']}</td></tr>";
}
?>
</table>
<?php
}
?>
For better readability I have displayed the data in table cells.
Simple Solution
You need to get multiple userIds from eventmember table which have multiple users against each event. But you are fetching only once from that query with $row = mysql_fetch_array($resultset);, So you should get only one user, what you are getting now. Hence, the problem is, you actually have put the while loop in a wrong place. The loop should be set like this :
$sql="SELECT userId FROM eventmember WHERE eventid='$event_id';";
$resultset = mysql_query($sql);
$num_row = mysql_num_rows($resultset);
if($num_row) {
while($row = mysql_fetch_array($resultset)) {
$sql22 = "SELECT userId, firstName FROM userinfo WHERE userId='{$row['userId']}';";
$resultset22 = mysql_query($sql22);
$row22 = mysql_fetch_array($resultset22);
$us_id = $row22['userId'];
$us_name = $row22['firstName'];
echo "<tr>";
echo "<td>ID:</td> <td class='text2' align='center' colspan='2'>
<b> $us_id </b>
</u></td>";
echo "</tr>";
//You shouldn't use a break here. This will again give you single result only.
}
}
A Better Solution
Instead of using multiple queries to get the data from userinfo table, use JOIN to get all data with one query. Like this :
$sql="SELECT u.userId,u.firstName FROM eventmember e JOIN userinfo u ON u.userId = e.userId WHERE e.eventid='$event_id';";
$resultset = mysql_query($sql);
$num_row = mysql_num_rows($resultset);
if($num_row) {
while($row = mysql_fetch_array($resultset)) {
$us_id = $row['userId'];
$us_name = $row['firstName'];
echo "<tr>";
echo "<td>ID:</td> <td class='text2' align='center' colspan='2'>
<b> $us_id </b>
</u></td>";
echo "</tr>";
}
}
The Best and Most Secure Solution
As you should have already known mysql_* functions are removed in PHP 7 and this functions are highly harmful for your security. So, you should either move to PDO or mysqli_* functions. I am giving here an example with mysqli_* functions and additionally I am fetching all rows at once instead of doing fetch for each row, which is better for performance.
//First setup your connection by this way.
$link = mysqli_connect(localhost, "my_user", "my_password", "my_db");
//Now you can use mysqli
$sql="SELECT u.userId,u.firstName FROM eventmember e JOIN userinfo u ON u.userId = e.userId WHERE e.eventid=?;";
$stmt = mysqli_prepare($link, $sql);
$stmt->bind_param('s', $event_id);
$stmt->execute();
$resultset = $stmt->get_result();
$resultArray = $resultset->fetch_all();
$num_row = count($resultArray);
if($num_row) {
foreach($resultArray as $row) {
$us_id = $row['userId'];
$us_name = $row['firstName'];
echo "<tr>";
echo "<td>ID:</td> <td class='text2' align='center' colspan='2'>
<b> $us_id </b>
</u></td>";
echo "</tr>";
}
}
mysql_fetch_array() will retrieve a single result from a result set. Therefore you'll need to wrap it in a loop to get each row/result.
Here's an example I ripped straight from the PHP documentation:
while ($row = mysql_fetch_array($result)) {
printf("ID: %s Name: %s", $row["id"], $row["name"]);
}
In your case you'd wrap the HTML code in the while loop.
An additional improvement would be to ensure that $resultset is a resource; mysql_query() can return false if your query is invalid (and true in other success cases like INSERTS). You can also use mysql_num_rows() to determine if you have >0 rows to display (and custom display a 'No rows returned' message).
Perhaps more importantly is that mysql_* functions were deprecated in PHP 5.5.0, and additionally removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL.
By continuing to write mysql_ code you'll make upgrading substantially more difficult for yourself. It's also worth noting that 5.5 will also reach security EOL in 6 months, leaving you to rely on your OS vendor to backport security updates from then on.
I have 2 tables in DB:
clients (Show all clients data)
clientsmany (admin could add many phone numbers for each client)
I would like to print all the details about the clients in 1 html table and if any client has more than phone number, all the numbers are printed in the same cell of 'td'
<?php
$result = mysql_query("SELECT * FROM clients");
$result1 = mysql_query("SELECT clientsmany.phone, clients.ID FROM clients INNER JOIN clientsmany ON clients.ID=clientsmany.ClientID");
while($row = mysql_fetch_array($result)){ //Not read!
while($row1 = mysql_fetch_array($result1)){ //Working correctly and show the list of 'phone' in $row1 for clientsmany.phone
echo "<center><table border='1'>";
echo "<tr><td>".$row['ID']."</td><td>".$row['phone']."<br>".$row1['phone']."</td></tr>";
echo "</table></center>";
}}
?>
Why the 1st while is not working??
The 2nd while only works and print a correct data then it exit automatic!
<?php
echo "<center><table border='1'>";
$result = mysql_query("SELECT * FROM clients");
while($row = mysql_fetch_array($result)){
$result1 = mysql_query("SELECT * FROM clientsmany WHERE clientsid=".$row['id']);
if(mysql_num_rows($result1)>0 ){
while($row1 = mysql_fetch_array($result1)){
echo "<tr><td>".$row['ID']."</td><td>".$row['phone']."<br>".$row1['phone']."</td> </tr>";
}
}else{
echo "<tr><td>".$row['ID']."</td><td>".$row['phone']."</td></tr>";
}
}
echo "</table></center>";
?>
Use GROUP_CONCAT to create a single query and you will be able to a single loop
GROUP_CONCAT will take a column that is repeated and separate each value with a comma (by default it can be changed) and return it into a single value
$query = <<<END
SELECT
clients.*,
GROUP_CONCAT(clientsmany.phone) as phonenums
FROM
clients
INNER JOIN
clientsmany ON clients.ID=clientsmany.ClientID
GROUP BY
clients.ID
END;
A query like this would give you all the clients table columns and a column named phonenums which will be a comma separated list of the phone numbers
Now since you only have one query you only need one loop
$db = mysqli_connect(...);
...
//only need to echo out the <table> part once
//so taken out of the while loop
echo "<center><table border='1'>";
$result = mysqli_query($db,$query);
while( ($row = mysqli_fetch_assoc($result)) ) {
echo <<<END
<tr>
<td>{$row['ID']}</td>
<td>{$row['SomeOtherColumn']}</td>
<td>{$row['phonenums']}</td>
</tr>
END;
}
//Again the </table> only needs done once
//so taken out of the loop
echo "</table></center>";
Notice the mysli_* functions being used. Mysql api is depreciated, for the most part you can just rename the functions you currently use to mysqli_, but note that some require the $db link as a parameter so make sure to read the php manual on each of the functions so you know how to call them correctly.
Also note that I am using heredoc syntax instead of doing multiple echo calls
First, mysql_* functions are depreciated. Try to use mysqli_* functions.
If you want to display data in 1 html table, so why you have started while above table tag?
Try this query..
SELECT clientsmany.phone, clients.* FROM clients, clientsmany WHERE clients.ID=clientsmany.ClientID"
Then use while statement below table tag (No need of 2 different while loop)...
echo "<center><table border='1'>";
while($row1 = mysqli_fetch_array($result1)) {
// your <tr><td> code
}
echo "</table></center>";
I created a website that has multiple logins and unique informations to it.. i want to retrieve the data from one user. example my username is qwert and my password is 1234, I want to retrieve his unique information to the database. I used the sample code in w3schools and it selects all the data but all I want to do is to retrieve the data from the user which is only logged in.
can anyone help me about this? any help will be much appreciated.
mysql_select_db("xone_login", $con);
$result = mysql_query("SELECT * FROM admin WHERE username = '$myusername' ");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['overtime'] . "</td>";
echo "<td>" . $row['daily_rate'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Replace the code in SQL in that tutorial with this (and adapt the table and column names) one:
SELECT * FROM USERS where name ='qwert' and pass = MD5('1234')
And take care at sanitizing your variables in order to avoid SQL injection attacks !
You need to use a where clause
Also you will need to specify limits on the query to restrict the result set to 1 record
$select = "SELECT * FROM usertable WHERE username = '$user' LIMIT 0, 1";
$query = mysql_query($select) or die(mysql_error());
$result = mysql_fetch_assoc($query);
//Prints the array
print_r($result);