Essentially, i'm trying to show the information about what the user has it lists their
BookID date time confirmed
confirmed is a 0 or 1, 0 is not confirmed 1 is confirmed, as this is a table this needs to be done with $_GET i'm assuming or it wont update the correct one.
at the moment I have this for the table listing the things
<?php
while($row = mysqli_fetch_array($result))
{ ?>
<tr>
<td><?php echo $row['BookID']?></td>
<td> <?php echo $row['date']?> </td>
<td> <?php echo $row['time']?> </td>
<td> <input type="checkbox" name="Confirmed" value="1" <?php echo ($row['Confirmed'] == 1) ? 'checked="checked"' : ''; ?>/> </td>
<td>Delete</td>
<td>Update</td>
</tr>
</table>
update.php contains this
<?php
// Your database info
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = 'smithrwg_database';
$Confirmed = $_POST['Confirmed'];
if (!isset($_POST['Confirmed']))
{
echo 'No ID was given...';
exit;
}
$con = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($con->connect_error)
{
die('Connect Error (' . $con->connect_errno . ') ' . $con->connect_error);
}
$sql = mysql_query("UPDATE tbl_booking SET Confirmed = '$Confirmed' WHERE BookID = ?");
//$sql = "UPDATE tbl_booking SET Confirmed='$Confirmed' WHERE BookID == ?";
if (!$result = $con->prepare($sql))
{
die('Query failed: (' . $con->errno . ') ' . $con->error);
}
if (!$result->bind_param('i', $_GET['BookID']))
{
die('Binding parameters failed: (' . $result->errno . ') ' . $result->error);
}
if (!$result->execute())
{
die('Execute failed: (' . $result->errno . ') ' . $result->error);
}
if ($result->affected_rows > 0)
{
echo "The ID was updated with success.";
}
else
{
echo "Couldn't update the ID.";
}
$result->close();
$con->close();
with my main focus being on the $sql, as it isnt actually getting the id from the get function.
the checkbox is getting the value from the database to see if it should be checked already or not, i want to be able to click it again and "un-confirm" or confirm it if it didn't have a tick.
What did you use for method attribute in your form tag? If you use GET, then use a GET to fetch it. If you use POST, then use a POST. By the way, try to echo all of the posted variables first so that you know that you are passing correct variable. It is always a good debugging method. Hope this helps. Thank you.
Related
This is a webpage that I have:
// Info to connect to the Wishlist database
$servername = "em";
$dbusername = "";
$password = "!19";
$dbname = "";
// To connect to the database please
$conn = new mysqli($servername, $dbusername, $password, $dbname);
// If unable to connect to the database display this error
if ($conn->connect_error) {
echo "Connection to wishlist failed";
die("Connection failed: " . $conn->connect_error);
}
echo "Once you have added creatures to your wishlist, click " .
"<strong><a href='http://eggcavity.com/edit-wishlist'>here</a></strong> to edit your wishlist.";
// Get current user's username
$current_user = wp_get_current_user();
$username = $current_user->user_login;
// Retrieve data from the database
$sql = "SELECT Name, Stage1 FROM Creatures";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// Display all of the data from the database
echo '<form method="POST">';
while($row = $result->fetch_assoc()) {
echo '<div style="display: inline-block; width: 30%;">' .
'<img src="' . $row["Stage1"] . '"><br>'.
$row["Name"] .
'<br><input type="checkbox" name="creautres[]" value="' .
$row["Name"] .
'"></div>';
}
echo '<br><br><input type="submit" value="Submit"></form>';
} else {
echo "Creatures not found";
}
if(isset($_POST['submit'])){
foreach($_POST['creatures'] as $selected){
$sql = "INSERT INTO " . $username .
" (Creature, Picture, Stage, Gender, Frozen, Notes) VALUES ('" .
$selected . "', 'http://static.eggcave.com/90x90/" . $selected .
"_1', 'Stage1', 'Unspecified', 'Unspecified', 'Unspecified', '')";
if ($conn->query($sql) === FALSE) {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
// Close the connection to the database
$conn->close();
It displays like I want it to:
But it doesn't update the database when I click the submit button.
I've tried echoing $stmt, it seemed to be written as it should be.
When I try echoing $selected, within the loop it doesn't seem to output anything.
Can you help me?
I have updated the code to use one database. Please help me. It still isn't adding.
You had a typo in your checkbox name. I re-did the submit line in the form and the isset() I believe.
The below includes activating error reporting, a try/catch, binding for safety against sql injection. The data saves. You will need to deal with what should be unique data getting saved more than once of course. For instance, a unique key on (Creature,Username). And I would re-think the columns for Id's, but this was your table design. Thanks for allowing us to show you a re-use of a table. Good luck.
schema (from you):
drop table if exists Wishlists;
CREATE TABLE `Wishlists` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Creature` varchar(100) DEFAULT NULL,
`Picture` varchar(200) DEFAULT NULL,
`Stage` varchar(100) DEFAULT NULL,
`Gender` varchar(100) DEFAULT NULL,
`Frozen` varchar(100) DEFAULT NULL,
`Notes` varchar(500) DEFAULT NULL,
`Username` varchar(100) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB; -- <------------------------ went with InnoDB
-- truncate table Wishlists; -- used during early testing
PHP (eggs01.php):
// Info to connect to the Wishlist database
$servername = "serve it up";
$dbusername = "dbu dbu dbu";
$password = "OpenSesame";
$dbname = "my db name";
try {
// To connect to the database please
$conn = new mysqli($servername, $dbusername, $password, $dbname);
if ($conn->connect_error) {
die('Connect Error (' . $conn->connect_errno . ') '
. $conn->connect_error);
}
echo "I am connected and feel happy.<br/>";
if(isset($_POST['submit'])){
// Postback - submit
// Get current user's username
//$current_user = wp_get_current_user(); // remmed out, I don't have your system
//$username = $current_user->user_login; // remmed out, I don't have your system
$theCount=0;
foreach($_POST['creatures'] as $selected){
$Creature=$selected;
$Picture="http://static.eggcave.com/90x90/" . $selected . "_1";
$Stage="Stage1";
$Gender="Unspecified";
$Frozen="Unspecified";
$Notes="Unspecified";
$Username="Stackoverflow123";
$sql = "INSERT Wishlists (Creature, Picture, Stage, Gender, Frozen, Notes, Username) " .
" VALUES (?,?,?,?,?,?,?)";
$stmt = $conn->prepare($sql); // SQL Injection - safe prepare / bind / execute
// 7 s's means 7 strings:
$stmt->bind_param('sssssss', $Creature, $Picture, $Stage, $Gender, $Frozen, $Notes, $Username);
$stmt->execute();
$theCount++;
}
echo "<br>Santa has been notified, count = ".$theCount."<br>";
}
else {
// Just display the form
// Retrieve data from the database
$result = $conn->query("SELECT Name, Stage1 FROM Creatures");
if ($result->num_rows > 0) {
// Display all of the data from the database
echo '<form method="POST">';
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
echo '<div style="display: inline-block; width: 30%;">' .
'<img src="' . $row["Stage1"] . '"><br>'.
$row["Name"] .
'<br><input type="checkbox" name="creatures[]" value="' .
$row["Name"] .
'"></div>';
}
echo '<br><br><button type="submit" name="submit">Submit</button></form>';
$result->close();
} else {
echo "Creatures not found";
}
}
} catch (mysqli_sql_exception $e) {
throw $e;
}
After the submit having selected 3 eggs:
Database Image:
First of all, look at code
$dbname1 = *****";
Here you are missing " :
So replace this with
$dbname1 = "*****";
and try again
First issue is you should never run a SQL statement in a Loop ALWAYS AVOID THIS - as it will put your server through a lot of strain.
And 2nd try this and tell me the out put
foreach($_POST['creatures'] as $selected){
$stmt = "INSERT INTO " . $username . " (Creature, Picture, Stage, Gender, Frozen, Notes) VALUES ('" . $selected . "', 'http://static.eggcave.com/90x90/" . $selected . "_1', 'Stage1', 'Unspecified', 'Unspecified', 'Unspecified', '')";
if ($conn->query($stmt) === TRUE) {
}
}
TO
foreach($_POST['creatures'] as $selected){
$stmt = "INSERT INTO " . $username . " (Creature, Picture, Stage, Gender, Frozen, Notes) VALUES ('" . $selected . "', 'http://static.eggcave.com/90x90/" . $selected . "_1', 'Stage1', 'Unspecified', 'Unspecified', 'Unspecified', '')";
$result = $conn->query($stmt) OR die(var_dump($conn));
var_dump($result->fetch_array(MYSQLI_ASSOC));
die;
}
I need to create a filled drop down list which is linked to my table called called 'dog' in phpmyadmin. I need a user to be able to select a dog from the list and press search and the results show up. And all information be stored in my table in phpmyadmin. This is what I have so far:
It doest work its just an empty drop down and it does nothing. Please help.
<?php
// set up connection parameters
$dbHost = 'hostnamegoeshere';
$databaseName = 'databasenamehere';
$username = 'usernamehere';
$password = 'passwordhere';
// make the database connection
$db = new PDO("mysql:host=$dbHost;dbname=$databaseName;charset=utf8","$username", "$password");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // enable error handling
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); // turn off emulation mode
?>
//Return an error if bad connection
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ')'
.$mysqli->connect_error);
}
//query database for results
$query = $mysqli->query("SELECT * FROM 'dog'");
?>
<h3> Search dogs</h3>
<select>
<?php
$stmt = $mysqli->prepare($query);
$stmt->execute();
$res = $stmt->get_result();
while($dropdown = $res->fetch_array(MYSQLI_ASSOC)) {
echo '<option value="' . $dropdown['dog'] . '"></option>';} ?>
</select>
I will be very grateful for any help
USE THIS
$res = $stmt->get_result();
$res =$res->fetch_array(MYSQLI_ASSOC)
foreach($res as $a){
echo '<option value="' . $a['dog'] . '">'. $a['dog'] .'</option>';} ?>
}
AT PLACE OF
$res = $stmt->get_result();
while($dropdown = $res->fetch_array(MYSQLI_ASSOC)) {
echo '<option value="' . $dropdown['dog'] . '"></option>';} ?>
Number of issues in your CODE
1) Wrap off quotes form table name(SELECT * FROM 'dog')quotes
2) Don't use prepare and query at one time.($mysqli->query,$mysqli->prepare)
3) Add text to your option(<option value="value"></option>)
4) You are mixing mysqli with pdo
You code would be
Create you connection with mysqli
$mysqli=mysqli_connect($dbHost,$username,$password,$databaseName);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ')'
.$mysqli->connect_error);
}
<h3> Search dogs</h3>
<select>
<?php
$stmt = $mysqli->query("SELECT * FROM dog");// wrap off and use only query to run
$stmt->execute();
$res = $stmt->get_result();
while ($dropdown = $res->fetch_array(MYSQLI_ASSOC)) {
echo '<option value="' . $dropdown['dog'] . '">'.$dropdown['dog'].'</option>';// add text to dropdown
}
?>
</select>
I have this problem with mysql on phpmyadmin databases that I want to update my database, for instance change the username, but with the current code I have, if I leave something empty, it updates the database with empty value, I wanted to change this that IF the post is empty it doesnt update the database to empty space
here is my code:
<!doctype html>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "eerstedatabase";
//create connection
$connection = new mysqli($servername, $username, $password, $dbname);
if ($_POST) {
//check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
//if these posts are empty it updates them to empty in the database aswell
$sql = "UPDATE gebruikers SET Gebruikersnaam='" . $_POST['Gebruikersnaam'] . "',
Wachtwoord='" . $_POST['Wachtwoord'] . "',
Email='" . $_POST['Email'] . "'
WHERE ID='" . $_POST['ID'] . "' ";
if ($connection->query($sql) === TRUE) {
echo "Record updated successfully";
include 'Opdracht1.php';
} else {
echo "Error updating record: " . $conn->error;
}
}
else
{
?>
<html>
<head>
<meta charset="utf-8">
<title>Naamloos document</title>
</head>
<body>
<center>
<table>
<form name="update" action="OpdrachtDW6.php" method="POST">
<tr>
<td>ID</td>
<td><input type="text" name="ID" rquired /></td>
</tr>
<tr>
<td>Gebruikersnaam</td>
<td><input type="text" name="Gebruikersnaam" required /></td>
</tr>
<tr>
<td>Wachtwoord</td>
<td><input type="text" name="Wachtwoord" required /></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="Email" required /></td>
</tr>
<tr>
<td><input type="submit" value="Updaten" /></td>
</tr>
</td>
</form>
</center>
</body>
</html>
<?php
}
?>
you can check if the POST values are empty or not:
if(empty($_POST['Email'])
// Do something
There are other options like check the length of string, if the name is too short, maybe it is not acceptable. Hope this help.
You need to check the value of the $_POST fields on the server side.
$errs = false;
if ($_POST['ID'] == "") {
$errs = true;
echo "ID Field Missing";
}
if ($_POST['Gebruikersnaam'] == "") {
$errs = true;
echo "Gebruikersnaam Field Missing";
}
/* And so on... */
if (!$errs) {
//check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
$sql = "UPDATE gebruikers SET Gebruikersnaam='" . $_POST['Gebruikersnaam'] . "',
Wachtwoord='" . $_POST['Wachtwoord'] . "',
Email='" . $_POST['Email'] . "'
WHERE ID='" . $_POST['ID'] . "' ";
if ($connection->query($sql) === TRUE) {
echo "Record updated successfully";
include 'Opdracht1.php';
} else {
echo "Error updating record: " . $conn->error;
}
}
You can use this logic
if(isset($_POST['Email'])){
//post email is not empty! and you can insert in database!
if ($connection->query($sql) === TRUE) {
echo "Record updated successfully";
include 'Opdracht1.php';
} else {
echo "Error updating record: " . $conn->error;
}
}
What I've done before is build my query into variables, then if a variable is empty it will skip that bit of the query.
For example
if($_POST['fielda']) {
$fieldasql = "fielda = '".$_POST['fielda']."',";
} else {
$fieldasql = "";
}
if($_POST['fieldb']) {
$fieldbsql = "fieldb = '".$_POST['fieldb']."',";
} else {
$fieldbsql = "";
}
then your query would be:
$sql = "UPDATE gebruikers SET " . $fieldasql . " " . $fieldbsql;
Here is the (basic) logic to check against (not) empty fields.
Sidenote: See comments in code to process as desired.
if( !empty($_POST['ID'])
&& !empty($_POST['Gebruikersnaam'])
&& !empty($_POST['Wachtwoord'])
&& !empty($_POST['Email'])
)
{
// Execute the query
}
else {
// kill the process or do something else
}
If you only want to perform the UPDATE if only the email is empty, then simply do:
if(!empty($_POST['Email'])) {
$sql = "UPDATE gebruikers ...
// Rest of your code
}
Consult the following on PHP's logical operators:
http://php.net/manual/en/language.operators.logical.php
and empty():
http://php.net/manual/en/function.empty.php
Footnotes:
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements.
Also on doing an UPDATE and to check if it truly was successful, use mysqli_affected_rows():
http://php.net/manual/en/mysqli.affected-rows.php
as if ($connection->query($sql) === TRUE) could give you a false positive.
You can also alter your column(s) to not accept NULL values.
Consult http://dev.mysql.com/doc/refman/5.7/en/working-with-null.html
and making it/them as NOT NULL.
On an added note, this if ($_POST) { could be changed to if(isset($_POST['submit'])){ and adding the submit name attribute to your submit button.
<input type="submit" name="submit" value="Updaten" />
So I have an issue getting rows to be deleted using the following code. The table displays the information correctly, plus sends the correct id in the url to the delete.php page, but I cannot get it to complete the command. Changing the code slightly on the delete.php I can get it to show either:
Couldn't delete the index.
or:
Binding parameters failed: 0
<?php
$con = mysqli_connect("localhost","user","pass","database");
// Check connection
if (mysqli_connect_errno())
{
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
if (!$result = mysqli_query($con,"SELECT * FROM mytable ORDER BY `server_name`;"))
{
die("Error: " . mysqli_error($con));
}
?>
<table border='1'>
<tr>
<th><b>Server Name</b></th>
<th><center><b>Port</b></center></th>
<th><center><b>Mod</b></center></th>
</tr>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row['server_name']; ?></td>
<td><center><?php echo $row['server_port']; ?></center></td>
<td><center><?php echo $row['mod']; ?></center></td>
<td><center><img src="images/remove.png" width="16" height="16"></center></img></td>
</tr>
<?php
}
mysqli_close($con);
?>
</table>
My delete file is
<?php
// Your database info
$db_host = 'localhost';
$db_user = 'user';
$db_pass = 'pass';
$db_name = 'database';
if (!isset($_GET['id']))
{
echo 'No ID was given...';
exit;
}
$con = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($con->connect_error)
{
die('Connect Error (' . $con->connect_errno . ') ' . $con->connect_error);
}
$sql = "DELETE FROM mytable WHERE 'index' = " . $_GET['id'];
if (!$result = $con->prepare($sql))
{
die('Query failed: (' . $con->errno . ') ' . $con->error);
}
if (!$result->bind_param('i', $_GET['ID']))
{
die('Binding parameters failed: (' . $result->errno . ') ' . $result->error);
}
if (!$result->execute())
{
die('Execute failed: (' . $result->errno . ') ' . $result->error);
}
if ($result->affected_rows > 0)
{
echo "The ID was deleted with success.";
}
else
{
echo "Couldn't delete the index.";
}
$result->close();
$con->close();
It has to be something simple but I cannot figure it out.
You're using the wrong type of quotes in your SQL. To escape a table or column name that contains a reserved word, you use backticks. And if you're using bind_param, you have to put ? in the query where the parameter will be substituted.
$sql = "DELETE FROM mytable WHERE `index` = ?";
Replace the following line in your delete.php file:
$sql = "DELETE FROM mytable WHERE 'index' = " . $_GET['id'];
with:
$sql = "DELETE FROM mytable WHERE `index` = ?";
Changes in the suggested replacement statement include:
Replace single quotes around column name index with backticks. Note that MySQL escape character is a backtick not single quotes.
You are not including any parameter placeholders in your delete query but further down you are attempting to bind an integer parameter.
Version 4:
I have taken away the pull down menu for now, I just want the info to be posting correctly.
As it shows with the first line fab1 shows #2, in the second line it shows 1, --None-- instead of 2, Andy Khal. If anyone can figure out why, it be appreciated. I've done about as much as I can to figure this out and I'm lost.
<?php
// Connect to the database.
require_once('tb/connectvars.php');
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
die("MySQL failed to connect: " . mysqli_connect_error());
}
// Create the SQL query
$testbed = "SELECT * FROM testbed";
$user = "SELECT * FROM user";
// Execute the SQL query and store the result set in
// the $result variable.
$testbed = mysqli_query($dbc, $testbed) or die("Failed to execute query on tesbed table: " . mysqli_error($dbc));
$user = mysqli_query($dbc, $user) or die("Failed to execute query on user table: " . mysqli_error($dbc));
// Read the results.
$row = mysqli_fetch_assoc($testbed);
if(!$row)
{
echo 'Query failed<br />';
}
else
{
echo "Query for Testbed Fabricator is : " . $row["fab1"] . "<br />";
}
$row = mysqli_fetch_assoc($user);
if(!$row)
{
echo 'Query for Testbed Fabricator failed<br />';
}
else
{
echo "Query for User ID # is : " . $row["userid"], $row["user"] . "<br />";
}
// Free the result set.
mysqli_free_result($testbed);
mysqli_free_result($user);
?>
Yes it is. You can specify the selected value with the selected keyword as a html attribute.
<option value="Username" selected>Username</option>
That makes this:
while($row = $result->fetch_assoc())
{
$user = $row['user'];
echo '<option value="' . $user . '"';
if($user is known)
{
echo ' selected';
}
echo '>' . $user . '</option>\n';
}
Update
In this snipped $choosen is the selected user's name.
echo'<div id="fab1">';
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$mysqli->select_db('user');
$result = $mysqli->query("SELECT * FROM user");
echo "<select name='fab1'>\n";
while($row = $result->fetch_assoc())
{
echo '<option value="' . $row['user'] . '"';
if($row['user'] == $choosen)
{
echo ' selected';
}
echo '>' . $row['user'] . '</option>\n';
}
echo "</select>\n";
echo '</div>';