i am trying display a the rows in my database table using the array of ids gotten from another table. i want it to display the first row which is $rowsfriend. and display the second row which is rows .......... but it only displays $rowsfriend
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ochat";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM friends where friend1='".($_POST[id])."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$rowsfriend = $row["friend2"];
echo $rows;
}
}
$sqll = "SELECT * FROM users WHERE id IN ($rowssfriend)";
$resultt = $conn->query($sqll);
if ($resultt->num_rows > 0) {
while($roww = $resultt->fetch_assoc()) {
$rowsss = $row["username"];
echo $rowss;
}
}
else {
?>
<h1>Register</h1>
<form action="selectfriends.php" method="post">
id:<br />
<input type="text" name="id" value="" />
<br /><br />
<input type="submit" value="enter" />
</form>
<?php
}
?>
Instead of two queries, you can write this nested query.
$sqll = "SELECT * FROM USERS WHERE ID IN (SELECT friend2 FROM friends WHERE friend1='".$_POST[$id]."')";
$resultt = $conn->query($sqll);
if ($resultt->num_rows > 0)
{
while($roww = $resultt->fetch_assoc())
{
$rowsss = $row["username"];
echo $rowss;
}
}
Hope this solve your problem .
Please try this version of code instead, if you might:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ochat";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT users.* FROM users WHERE users.id IN (SELECT friend2 FROM friends where friend1='".($_POST[id])."')";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$rows = $row["username"];
echo $rows;
}
}
else {
?>
<h1>Register</h1>
<form action="selectfriends.php" method="post">
id:<br />
<input type="text" name="id" value="" />
<br /><br />
<input type="submit" value="enter" />
</form>
<?php
}
?>
As far as I understood the code well, the problem was with the variable name typo as #Admieus wrote but also in the fact that in each iteration of the first loop variable $rowsfriend got overriden with a new value so after the end of the loop, $rowsfriend contained the last id from the result of the first query $sql.
The above version makes only one query using subquery in it to get directly usernames who are friends of friend1 given in $_POST[$id].
I hope it helps.
There are typos in the second loop.
You assign the value to $rowsss and try to echo from $rowss notice the difference.
Also, you assign the fetch_assoc result to $roww and then try to call it again with $row.
$sqll = "SELECT * FROM users WHERE id IN ($rowsfriend)";
$resultt = $conn->query($sqll);
if ($resultt->num_rows > 0) {
while($roww = $resultt->fetch_assoc()) {
$rowsss = $roww["username"];
echo $rowsss;
}
}
Point of improvement is: check your variable names, make names that are easy to understand and hard to mix up.
For instance, the variable containing the sql query should not be named $sql and to make it worse a second query shoul not be named sqll. Instead use names that imply what you are doing.
$querySelectFriendsFrom = "SELECT * FROM users WHERE id IN ($friendId)";
Don't take this as a hard rule, it's more of a tip to prevent silly mistakes.
Update: there was also a type in the query referring to rowssfriend instead of rowsfriend. Fixed above.
Related
I'm trying to get a value from the database and compare it with whatever id href was set. But nothing happens.
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "products";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id FROM items";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$id = $row["id"];
echo <<<EOT
<br>
<form action='index.php?$id' method="POST">
<input type='submit' name="submit" value="more">
</form>
EOT;
}
} else {
echo "0 results";
}
if (isset($_POST['submit'])) {
while($row = $result->fetch_assoc()) {
if ($_SERVER["QUERY_STRING"] == $row) {
echo 'you clicked something from the database' . $id;
}
}
}
$conn->close();
?>
Trying to eventually get a value from the database then individually show a description if the more href is clicked.
your answer has a high time complexity you can easily make you
SQL query
SELECT id FROM items WHERE id = ?
and if the rows number is 0 this is mean there is no record with this id
you can check row's number from num_rows
You will never see "you clicked something from the database" message because you already fetched the result from your query in the first loop, check this question why-cant-i-loop-twice-on-mysqli-fetch-array-results
An option is to save the result in an array to use it later in your second loop
//your first loop
$savedRows = [];
while($row = $result->fetch_assoc()) {
$savedRows[] = $row;
//the rest of your code
}
// ......
// your second loop
if (isset($_POST['submit'])) {
foreach($savedRows as $row) {
if ($_SERVER["QUERY_STRING"] == $row['id']) {
echo 'you clicked something from the database ' . $id;
}
}
}
Also note that if this is your actual code, you need to make the closing identifier of your herodoc EOT; the first character on it's line, otherwise the rest of the file will be part of this string
I have HTML code with checkbox and submit button as below
<form action="checkboxes.php" method="post">
<input type="checkbox" name="checkbox1" value="Yes">4K</input>
<input type="submit" name="formSubmit" value="Submit" ></input>
</form>
And in my PHP I have a file "config.php" that his function is to connect to my database:
<?php
/* Database connection */
$sDbHost = 'localhost';
$sDbName = 'testowanie';
$sDbUser = 'root';
$sDbPwd = '';
$dbcon = mysqli_connect ($sDbHost, $sDbUser, $sDbPwd, $sDbName);
?>
And a second PHP file:
<?php
include('config.php');
$sqlget = "SELECT * FROM monitory";
$sqldata = mysqli_query($dbcon, $sqlget)or die("Can't connect to the database");
if(isset($_POST['checkbox1']) &&
$_POST['checkbox1'] == 'Yes')
{
while($row = mysqli_fetch_array($sqldata, MYSQLI_ASSOC)) {
echo '.';
echo $row['cena'];
}
}
?>
This all three connected files each others do that if the checkbox is checked this SQL statement are executed: SELECT cena FROM monitory; but I want to execute this statement "SELECT * FROM monitory WHERE cena=1000;
I tried to do this like around 2 hours but I really don't know how to do this.
So You want to choose one of two different queries according to input conditions. Then do it so :-)
<?php
include('config.php');
if (isset($_POST['checkbox1']))
$sqlget = "SELECT * FROM monitory WHERE cena = 1000";
else
$sqlget = "SELECT * FROM monitory";
$sqldata = mysqli_query($dbcon, $sqlget)or die("Can't connect to the database");
while($row = mysqli_fetch_array($sqldata, MYSQLI_ASSOC)) {
echo '.';
echo $row['cena'];
}
I am trying to create a form where everything is filled out from the user's previous entry. Its suppose to work by the user selecting the "update" link. However the form is not being filled at all.
I've been trying to figure this out for 2 days now but i cant seem to figure it out. Some help would be greatly appreciated, thanks!
up.php
<form method="POST" action="up1.php">
<?php
$connection = mysql_connect("xxxxx","xxxxx","xxxxx")
or die("Could not make connection.");
$db = mysql_select_db("xxxxx")
or die("Could not select database.");
$sql1 = "SELECT * FROM emp ORDER BY primeID DESC ";
$sql_result = mysql_query($sql1) or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_array($sql_result))
{
$prime = $row["primeID"];
}
?>
Update
</form>
up1.php
<form action="up2.php" method="post">
<?
$connection = mysql_connect("xxxxx","xxxxx","xxxxx")
or die("Could not make connection.");
$db = mysql_select_db("xxxxx")
or die("Could not select database.");
$sql1 = "SELECT * FROM emp WHERE primeID = '$up22'";
$sql_result = mysql_query($sql1)
or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_array($sql_result))
{
$prime = $row["primeID"];
$a1 = $row["country"];
$a2 = $row["job"];
$a3 = $row["pos_type"];
$a4 = $row["location"];
$a5 = $row["des"];
$a6 = $row["des_mess"];
$a7 = $row["blurb"];
$a8 = $row["restitle"];
$a9 = $row["res"];
$a10 = $row["knowtitle"];
$a11 = $row["know"];
$a12 = $row["mis"];
$a13 = $row["mis_des"];
}
?>
<input name="aa1" value="<? echo $a1; ?>" type="text" id="textfield" size="60">
<input name="a1" type="text" value="<? echo $a2; ?>" id="textfield" size="60">
<input name="a2" type="text" value="<? echo $a3; ?>" id="a2" size="60">
<input name="a4" type="text" value="<? echo $a5; ?>" id="a4" size="60">
</form>
Based upon the limited information I could get out of your post I think I found the problem:
Starting with up.php
Update
Actually sends a "GET request" (Loading the page with a query string). We need to rebuild that:
<a href="JavaScript: void(0)" onclick="this.parentElement.submit()" >Update</a>
Now this link is going to send the form. However we need to send the value $prime. Let's use a hidden input inside the form.
<input type="hidden" name="up22" value="<? echo $prime; ?>" />
Now when the user clicks the link it posts the form and loads up1.php with the post var up22.
Changes to up1.php
$sql1 = "SELECT * FROM emp WHERE primeID = '".$_POST['up22']".'";
PDO
To update your code even further: PDO is a safer way to do queries. mysql queries are deprecated. They shouldn't be used anymore.
Replace your database calls with the following code:
function openDBConnection()
{
$name = "xxxxxx";
$pw = "xxxxxx";
$server = "xxxxxxx";
$dbConn = new PDO("mysql:host=$server;dbname=xxx", $name, $pw, , array( PDO::ATTR_PERSISTENT => false));
}
catch( PDOException $Exception )
{
echo "120001 Unable to connect to database.";
}
return $dbConn;
}
function doPDOQuery($sql, $type, $var = array())
{
$db = openDBConnection();
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
if ($type == "prepare")
{
$queryArray = $var;
$sth = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute($queryArray);
}
else if ($type == "query")
{
$sth = $db->query($sql);
}
else
{
echo "Supplied type is not valid.";
exit;
}
if (!$sth)
{
$error = $db->errorInfo();
echo $error;
exit;
}
return $sth;
}
These functions you can use to make PDO queries to the database. The first function opens a database connection, while the second functions actually performs the query. You do not need to call the first function. It's called in the second one.
Example based upon your code:
$sql1 = "SELECT * FROM emp WHERE primeID = :id";
$sql_result = doPDOQuery($sql1, 'prepare', array(":id" => $_POST['up22']));
while ($row = $sql_result->fetchAll() )
{
//loop through the results.
}
PDO works as follows: instead of passing php variables into the SQL string (and risking SQL-injection), PDO passes the SQL string and variables to the database and let's the database's driver build the query string.
PDO variables can be declared by name or by index:
By name: use : to declare a named variable. SELECT * FROM TABLE WHERE id = :id. Each key must be unique.
By index: use ? to declare an indexed variable. SELECT * FROM TABLE WHERE id = ?
An array containing the variables needs to be passed to PDO.
named array:
array(":id" => 1);
indexed array:
array(1);
With named arrays you don't have to worry about the order of the variables.
http://php.net/manual/en/book.pdo.php
I'm trying to bring data from MYSQL Database called ebms_db. The table is events and the fields are Event_ID and Event_Name.
The code I'm using currently to show the Event_Name only in the dropdown list is:
<select name="mySelect">
<?php
include 'db.php';
$sql = "SELECT Event_Name FROM events";
$result = mysql_query($sql);
echo "<select name='Event_Name'>";
while ($r = mysql_fetch_array($result)) {
echo '<option value="'.$row["Event_Name"].'">'.$row["Event_Name"].'</option>';
}
echo "</select>";
?>
<input type = "submit" name="Search" value="Search">
</select>
Db.Php looks like this...
$servername = "localhost";
$username = "test";
$password = "test";
$dbname = "ebms_db";
$conn = new mysqli($servername, "test", "test", $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
echo "Error";
}
What am I doing wrong?
The output shows a combo box with
- '.$row["Events_Name"].'
inside it.
while ($row = mysql_fetch_array($result)) {
^^^^ here
echo '<option value="'.$row["Event_Name"].'">'.$row["Event_Name"].'</option>';
}
<?php
include 'db.php';
// you just fetching here (Event_Name) take all the values from the database or
$sql = "SELECT * FROM events";
$result = mysql_query($sql);
echo "<select name='Event_Name'>";
while ($row = mysql_fetch_array($result)) {
echo '<option value="'.$row["Event_Name"].'">'.$row["Event_Name"].'</option>';
}
echo "</select>";
?>
<input type = "submit" name="Search" value="Search">
Why are you taking two selects? I just removed one select just beginning above the php tags.
MYSQL is deprecated, you should really use something else, if and/or when they remove it your website will be defunct.
i'm farly new to php and are trying to make a php script where it's suppose to connect to a mysql db and get the vaule id, then show as an option in a drop down menu.
This is the code I have so far (got help from a friend):
$username = "root";
$password = "";
$hostname = "localhost";
$database = "customers";
$id = "";
mysql_connect("$hostname", "$username", "$password") or die (mysql_error()) or die (mysql_error());
mysql_select_db("$database") or die (mysql_error());
$result = mysql_query("SELECT id FROM users WHERE id='$id'") or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$valuestring = $row['id'];
print_r($result);
echo "<option value='$valuestring'>". $valuestring ."</option>";
mysql_close();
}
print_r($id);
But when I use this code the option is returned empty :/
I have also tried to do print_r($result); and that give me Resource id #4, so I guess that works.
If anyone could help me solve this I would be one happy guy :D
the $id value in your code is empty, are you avare of that ?
and can you print the query before sending it to mysql ?
use :
"$query = "select id from table where id = '$id'";
mysql_query($query);
echo $query;
Perhaps if you showed us what output you did get it would help.
the option is returned empty
If the output includes HTML generated inside the loop then that means the query returned at least 1 row. But the only way that echo "<option value='$valuestring'>" would produce an empty string is if $valuestring was an empty string. It's populated from "SELECT id FROM users WHERE id='$id'" implying that you must have a row in your database where id is null or an empty string and $id in your php code is null/empty string - indeed that is the case ($id = "";).
NTW the mysql_close(); should be outside the loop.
Let's simplify this code:
<select name="user" id="user" width="200px" style="width: 200px">
<option value="">Select State</option>
<?php
$query_uf = "SELECT id FROM users WHERE id="'.$id.'";
$result = mysql_query($query_uf,$bd);
while ($users =mysql_fetch_assoc($result)) {
echo "<option value='".$uf['id']."'>".$uf['user']."</option>"; }
?>
</select>
Obs: It's better you use mysqli_query and connect. And, in your code it's missing the connection in mysql_query.
I've previously needed to retrieve a list of albums from a table using a similar method, maybe try this function. Create your form and call the function within the and tags leading this to work. This should list your id(s) where specified in the query.
functions.php (or wherever you'd like to put the function):
function stateList() {
$username = "username";
$password = "password";
$host = "localhost";
$dbname = "dbname";
$id = RETRIEVE VALUE HERE;
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
$query = "
SELECT
id,
FROM users
WHERE
id = $id // YOU MAY WANT TO REMOVE WHERE - $ID AS STATED ABOVE, DOESN'T MAKE SENSE.
";
try
{
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$valuestring = $row['id'];
$rows = $stmt->fetchAll();
foreach($rows as $row):
print "<option value='" . $valuestring . "'>" . $valuestring . "</option>";
endforeach;
}
?>
Selection page:
<? include 'functions.php' ?> <!-- This will allow you to call the function. -->
<form action="example.php" method="post" enctype="multipart/form-data">
<select name="album">
<? stateList(); ?> <!-- Calls the function and retrieves all options -->
</select>
<input type="submit" name="submit" value="Submit">
</form>