I have this code to have a list of my field in a database.
I have to select one of this element and modify it.
<?php
mysql_connect("*", "*", "*") or die("Connection Failed");
mysql_select_db("Sql860043_2")or die("Connection Failed");
$query = "SELECT * FROM users";
$result = mysql_query($query);
?>
<select name="select1">
<?php while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { ?>
<option value="Test">
<?php echo $line['firstname'];?>
</option>
<?php } ?>
</select>
This is the result:
http://www.mobilesystemsas.it/ale/test1/test1.php
For example i want to select "Alessandro" and modify it to "Giuseppe".
How i can do it?
Wrap the select tag in a form tag, and set its action attribute to the current php script.
Before performing the query to select all users, check the $_POST superglobal for the name of your select tag. If it is set, perform a MySQL UPDATE statement with that value on the given user.
Here is an example from w3schools:
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Note: You may want to also include a hidden tag within the form to store the User's ID, which will be necessary in your UPDATE statement.
Related
This question already has answers here:
PHP PDO group query results by column name
(2 answers)
Closed 3 years ago.
Beginner here, be gentle please. I have a table in which one column is book titles and another is their corresponding authors. I'm using PDO to connect to the database and display the results of a query on a webpage. Basically I want each UNIQUE author displayed once, and then a list of each book title that author wrote beneath, like so:
Author 1
title1
title2
Author 2
title3
title4
Query to get a list of distinct authors:
<?php try {
$connection = new PDO($dsn, $username, $password, $options);
$sql = "SELECT DISTINCT author FROM booktable;"
$statement = $connection->prepare($sql);
$result = $statement->fetchAll();
} ?>
Foreach loop to display each author:
<?php foreach ($result as $row) { ?>
<p><?php echo ($row["author"]); ?></p>
<?php } ?>
So far so good, this gives me a list of unique authors. For the titles, I was trying to do another foreach loop nested inside the first to display a second query, but I can't figure out how to get only the author the loop is currently on. I tried setting a variable inside the loop like so:
<?php foreach ($result as $row) { ?>
<p><?php echo ($row["author"]); ?></p>
<?php $currentauthor = ($row["author"]); ?>
<?php foreach ($result2 as $row2) { ?>
<p><?php echo ($row2["title"]); ?></p>
<?php } ?>
<?php } ?>
And then adding another query in my original TRY (along with a corresponding new connection and fetch statement):
$sql2 = "SELECT * FROM booktable WHERE author = '$currentauthor'";)
But that returns nothing because the $currentauthor variable doesn't exist outside the foreach loop. So there's my issue. Am I going about this the wrong way?
It looks like you should be able to do what you are attempting with a single, non-joining query. You can use SELECT * FROM booktable ORDER BY author, and loop through it's results, only outputting author data when you detect the current record has a different author than the previous one (and for the first record obviously).
A note since you're new: the * in SELECT * is generally considered bad form for final, deployed queries; I merely used it here as a placeholder since I do not know all the fields you want data from. It is best to specify all the fields you will be using, as it: (1) documents the data used without having to inspect all code that works with the data, (2) makes the query less fragile by not depending on the table definition for column order, (3) makes the query break if a used field is removed from the table, rather than later code that assumes the value will be there (which then has to be tracked back to the query), (4) keeps the amount of data that needs to be collected together and transferred to only what is needed, and (5) more...
I can't figure out why the posts from my form won't save in the database.
This is the html:
<button type="button" class="write">Write Reviews</button>
<form class="writeForm"method="post">
<input type="text" required name="monicker" placeholder="Name">
<textarea name="review" required maxlength="5000" placeholder="Leave your review here (max 25,000 charachters)"></textarea>
<input type="submit" value="Submit">
</form>
And the php:
<?php
$dbc = mysqli::real_connect('localhost', 'user_name', 'not_password');
mysqli::select_db('db_name',$dbc);
$monicker = mysqli::real_escape_string ($_POST['monicker']);
$review = mysqli::real_escape_string ($_POST['review']);
if(isset($_POST['Submit'])) {
$query = "INSERT INTO reviews
(id, monicker, review, date)
VALUES (DEFAULT,'$monicker', '$review', 'CURDATE()');";
mysqlI::query($dbc, $query);
}
mysqlI::close();
?>
As #maku said, you need to execute the query. But there is also more to it.
You have added $mysql_query, this is incorrect.
It is the wrong API (mysql vs. mysqli).
You also need to include your db connection.
If your id column is auto_increment, there is no need to insert it. Happens automatically.
There is no reason to assign a variable to the query because you are not selecting anything.
I would recommend using prepared statements instead, then you don't need to use mysqli::real_escape_string.
if(isset($_POST['submit'])) {
$query = "INSERT INTO reviews (id, monicker, review, date)
VALUES (DEFAULT,'$monicker', '$review', 'CURDATE()')";
mysqli_query($dbc, $query) or die(mysqli_error($dbc);
}
mysqli::close();
You didnt execute your query :
Add this line.
$result = $mysqli::query($query);
I modified your code, please check this code :
<?php
$dbc = mysql_connect('localhost', 'communi3_root', 'typeset');
mysql_select_db('communi3_cfds',$dbc);
$monicker = isset($_POST['monicker']) ? mysql_real_escape_string ($_POST['monicker']) : '';
$review = isset($_POST['review']) ? mysql_real_escape_string ($_POST['review']) : '';
if(isset($_POST['submit'])){
$current_date = date('Y-m-d H:i:s');
$query = "INSERT INTO reviews (id, monicker, review, date) VALUES (DEFAULT,'$monicker', '$review', '$current_date');";
$result = mysql_query($query)or die(mysql_error($dbc));
}
mysql_close();
?>
I found an issues in your previous code :
1. No checking on your POST variables. It causes error because you used it directly without checking if it is set or not.
2. CURDATE() is an undefined function, use PHP date function instead.
I've created an admin panel on my website so when the admin logs in he can edit users. I'm trying to get it to create a table that displays a list of all the users on the database, however, when I run it I get the error:
No database selected
Here is the code in my editusers.php:
<?php
include 'adminpage.php';
include 'connection.php';
$sql = "SELECT * FROM Users";
$result = mysql_query($sql)or die(mysql_error());
echo "<table>";
echo "<tr><th>UserID</th><th>First Name</th><th>Last Name</th><th>Email</th><th>D-O-B</th></tr>Username</th><th>Password</th><th>";
while($row = mysql_fetch_array($result)){
$userid = $row['UserID'];
$firstname = $row['FirstName'];
$lastname = $row['LastName'];
$email = $row['Email'];
$dob = $row['DateofBirth'];
$username = $row['Username'];
$password = $row['Password'];
// Now for each looped row
echo "<tr><td style='width: 200px;'>".$userid."</td><td style='width: 200px;'>".$firstname."</td><td>".$scale."</td><td>".$lastname."</td><td>".$email."</td></tr>".$dob."</td></tr>".$username."</td></tr>".$password."</td></tr>";
} // End our while loop
echo "</table>"
?>
First of all it looks like you are using mysql which isn't a wise move. This is because Mysql is actually deprecated and was improved to mysqli. Your problem may be to do with your database connection. You also haven't set a database. Like I said you can set an active database in your connection script. It should or could look something like this.
<?php
$conn = mysqli_connect("localhost", "root", "password", "database");
// Evaluate the connection
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
exit();
}
?>
After that, your sql query is correct by selecting all from you table 'users' but in order to proceed I recommend creating a query where you use mysqli_query an select the $sql and $conn as parameters. In all honesty it is much advised to stop and continue once you have adapted to mysqli. Alternatively you can use PDO which in some cases can be seen as better to use rather than mysqli but the choice is yours. I personally would get to grips with mysqli and then look at some answers on Stack Overflow to decide whether you should use PDO or not. Visit the PHP manual here. Enter all the mysql functions you know and it will show you how to use the new mysqli version of the functions. Don't think that it is as simple as just adding and 'i' to the end of a mysql function. That's what I initially thought but there is alot to do with extra parameters etc. Hope this helps :-)
So ive got a fully working page to display a dropdown list of all tables avaliable in my database. however i want it to display the list of all tables except one (as one of the tables contains user information which i dont want shown...)
Is there a way to do this?
This is the section of the code ive got so far...
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
if (mysql_select_db($dbname, $conn))
{
?>
<form method="post" action="Browse.php">
<select name="tables">
<?php
while ($row = mysql_fetch_row($result)) {
?>
<?php
echo '<option value="'.$row[0].'">'.$row[0].'</option>';
}
?>
</select>
<input type="submit" value="Show">
</form>
<?php
//mysql_free_result($result);
if (isset($_POST) && isset($_POST['tables']))
{
$tbl=$_POST['tables'];
//echo $_POST['tables']."<br />";
$query="SELECT * from $tbl ORDER BY title ASC";
$res=mysql_query($query);
//echo $query;
if ($res)
{
?>
<table border="1">
<?php
while ( $row = mysql_fetch_array($res))
{
echo "<tr>";
//echo "<td>".$row[0]."</td>";
echo "<td>".$row[1]."</td>";
//echo "<td>".$row[2]."</td>";
//echo "<td>".$row[3]."</td>";
echo "</tr>";
} ?>
</table>
<?php
}
}
}
Its no biggie if there isnt an easy way to do so as i've figured out that by doing the $query="SELECT * from $tbl ORDER BY title ASC"; it wont display the data (as there isnt a title column in the user details table)..but i dont want the table name to be shown in the dropdown box
Just a general query really...
Thanks
You can use a where clause with the SHOW TABLES statement.
The trick is knowing the name of the column that's generated by the SHOW TABLES statement as its name depends on your database name. The name of the column will be "tables_in_{your_dbname}". So if your database name is "blah" the column name will be "tables_in_blah".
So if the table you want to omit from your result set is called "secret_table" you can execute the statement like so:
SHOW TABLES WHERE tables_in_blah <> 'secret_table';
Or if you want to use a wildcard you can do it like so:
SHOW TABLES WHERE tables_in_blah NOT LIKE '%secret_table%';
Try this:
SELECT table_name FROM information_schema.tables
WHERE table_schema = 'your_data_base_name'
AND table_name NOT LIKE '%USER_TABLE%';
Without like
SELECT table_name FROM information_schema.tables
WHERE table_schema = 'your_data_base_name' AND table_name <> 'USER_TABLE';
Another alternative is to avoid outputting the table in question when you construct the list of options:
<?php
while ($row = mysql_fetch_row($result)) {
if ($row[0] != 'my_private_table_name') {
echo '<option value="'.$row[0].'">'.$row[0].'</option>';
}
}
?>
I'm using PHP to make a very specific sql query. For example sake, I have the user's ID number, but I need their name. So I do a sql query from that table with the ID number in order to return the name.
$result = mysql_query("SELECT name FROM users WHERE userID=$thisuserid",$db);
Now I want to use that. What's the most succinct way to go about making that result into a variable ths I can use?
edit:
I'm hoping that this is not the answer:
$rowCheck = mysql_num_rows($result);
if ($rowCheck > '0') {
while ($row = mysql_fetch_assoc($result)){
foreach ($row as $val){
$username = $val;
}
}
}
I have used something like this to keep it short in the past:
list($name) = mysql_fetch_row(mysql_query("SELECT name FROM users WHERE userID=$thisuserid",$db));
echo $name;
In my opinion, the best way to fetch any SQL result is through mysql_fetch_assoc(). To use it, you would do something like this:
$result = mysql_query("SELECT name FROM users WHERE userID=$thisuserid",$db);
while ($row = mysql_fetch_assoc($result)) {
echo $row['name']; // You get an array with each column returned from your query.
}
Still, MySQL extension has been replaced for MySQLi, which is acknowledged to be faster and more practical. It has both OOP and structural bindings, and takes more into account your server settings.
$result = mysql_query("SELECT name FROM users WHERE userID=$thisuserid",$db);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$name = mysql_fetch_row($result)[0];
You should use MySQLi as bellow:
$db = new MySQLi($host,$user,$pass,$db);
$query = $db->query('SELECT name FROM users WHERE userID='.$thisuserid);
$result = $query->fetch_object();
echo $result->name;
If you use SELECT * so you also can access via $result->{field_name}