I have a form I'm using to send multiple fields with a similar name but using square brackets to send them as an array with the key being 'id'. I am able to loop through successfully using a foreach loop but my insert query fails to make any changes in the db.any clues as to why?
here is the code from the form:
$artist = mysql_fetch_array($allartists);
$allmusic = get_music_for_artist($artist_id);
$id = $music['id'];
while ($music = mysql_fetch_array($allmusic)) {
echo "<td class=\"td20 tdblue\">
<input name=\"song_title[" . $id . "]\" type=\"text\" value=\"" . $music['song_title'] . "\" />
</td>";
}
and here is the code on my form processor
foreach ($_POST['song_title'] as $id => $song) {
$query = "UPDATE music SET
song_title = '{$song}'
WHERE id = $id ";
if (mysql_query($query, $connection)) {
//Success
header("Location: yourmusic.php?pid=3");
exit;
} else {
//Display error message
echo "update did not succeed";
echo "<p>" . mysql_error() . "</p>";
}
}
Try this.
Also watch for security http://www.phptherightway.com/#data_filtering
foreach ($_POST['song_title'] as $id => $song) {
$id = (int) $id;
$song = mysql_real_escape_string($song);
$query = "UPDATE music SET
song_title = '$song'
WHERE id = $id LIMIT 1;";
if (mysql_query($query, $connection)) {
//Success
header("Location: yourmusic.php?pid=3");
exit;
} else {
//Display error message
echo "update did not succeed";
echo "<p>" . mysql_error() . "</p>";
}
}
Related
I have made a blog in PHP, on Post.php with If isset get I am checking Post ID and than getting slug of same ID from database and accessing the post with that slug.
The issue is its generating Url like: Post.php?Slug=postname-title
I want to make it Post.php?postname-title OR urls.com/postname-title
Please note I am getting post from database matching with slug If any how I do not set php to Get in url it is not getting value from the same slug.
Please guide if it will be done via .htaccess or any other way?
<?php
// add mysql_real_escape_string to slug, to prevent sql injection
$slug = $_GET["slug"];
$sql = "SELECT * FROM posts WHERE slug = '" . mysqli_real_escape_string($db, $_GET["slug"]) . "'";
$result = mysqli_query($db, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while ($row = mysqli_fetch_assoc($result)) {
echo "<h2>" . $row["title"] . "</h2>";
echo "<div id='post-details'>" . "Posted on " . $row["post_date"] . " -- " . "Last Update " . $row["last_edited"] .
"</div>";
if (loggedin()) { echo "<div id='postactions'>This Post:<a href='create_note.php?id=" . $row["id"] . "'>Add Notes</a>";
echo 'Delete Post';
echo 'Edit</div>'; }
$cat_id = $row["cat_id"];
$sql = "SELECT * FROM categories WHERE id = $cat_id";
$resultone = mysqli_query($db, $sql);
if (mysqli_num_rows($resultone) > 0) {
// output data of each row
while ($rowone = mysqli_fetch_assoc($resultone)) {
$cat_name = $rowone["name"];
echo "<div id='post-category'>" . "Category: <a href='all-categories.php?cat_id=$cat_id'>$cat_name</a>" . "</div>";
}
}
echo "<p>" . htmlspecialchars_decode($row["body"]) . "</p>";
$_SESSION["post_id"] = $row["id"];
$postid = $row["id"];
}
} else {
echo "0 results";
}
?>
If you want a simple .htaccess version, you could use the following rule:
RewriteRule ^post/(.+) Post.php?Slug=$1
This will change your URL from a pretty URL like: yourdomain.com/post/postname-title to yourdomain.com/Post.php?Slug=postname-title
So i have this code to display all the users in my database and to access them. That works fine but is there any way to get where it says click here just to display a variable in this case the leader name(aka user name)?
<?php
require_once "config.php";
$sql = "SELECT id , leader_name, nation_name, power FROM nation_info";
$result = $link->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$nationList = [];
$userid = $row['id'];
echo ' click here '; // the click here on this line
// echo '<a class="viewProfile" href="viewnation.php?id=' . $userid . '"><button>View Profile</button></a>'; old method of viewing profile
echo " Nation Name: " . $row["nation_name"]. " Leader Name " . $row["leader_name"]. " Power " . $row["power"];
echo "<br>";
}
} else {
echo "0 results";
}
$link->close();
?>
Are you talking about this? Just printing the name in place of click here?
<?php
require_once "config.php";
$sql = "SELECT id , leader_name, nation_name, power FROM nation_info";
$result = $link->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$nationList = [];
$userid = $row['id'];
echo ' ' . $row["leader_name"] . ' '; // the click here on this line
// echo '<a class="viewProfile" href="viewnation.php?id=' . $userid . '"><button>View Profile</button></a>'; old method of viewing profile
echo " Nation Name: " . $row["nation_name"]. " Leader Name " . $row["leader_name"]. " Power " . $row["power"];
echo "<br>";
}
} else {
echo "0 results";
}
$link->close();
?>
I am creating a multiuser shared to do list application using PHP and MySQL. Currently, my application is displaying the to do list items by iterating over the database table with a while loop.
All of that works correctly, so I know I am connecting to the database. Part of the while loop also generates buttons that allow a user to "claim" an item that does not have anyone working on it or to indicate that at item has been completed. However, the buttons are not updating the database table.
<?php
include 'includes/dbh.inc.php';
$sql = 'SELECT * FROM items WHERE item_is_done = 0';
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
$creator = $row['item_creator'];
$owner = $row['item_owner'];
$id = $row['item_id'];
if (isset($_POST['do_item'])) {
$update = "UPDATE items SET item_owner = $currentID WHERE item_id = $id;";
mysqli_query($conn, $update);
header("Location: ../todo.php?code=doing");
exit();
} else if(isset($_POST['complete_item'])) {
$update = "UPDATE items SET item_is_done = 1 WHERE item_id = $id;";
mysqli_query($conn, $update);
header("Location: ../todo.php?code=done");
exit();
}
echo '<h4>Item ID:</h4>' . $id . '<br><br>';
echo '<h4>Item created by:</h4>' . $creator . '<br><br>';
echo '<h4>Date Added: </h4>' . $row['item_add_date'] . '<br><br>';
echo '<h4>Item Title: </h4>' . $row['item_title'] . '<br><br>';
echo '<h4>Description: </h4>' . $row['item_description'] . '<br>';
if($row['item_owner'] == 'None') {
echo '<br>';
echo '<button type="submit" name="do_item" formaction="todo.php" formmethod="POST">Do Item</button>';
echo '<br>';
} else if($row['item_owner'] != 'None') {
echo '<br>';
echo '<h4>Item is being worked on by: </h4>' . $owner . '<br><br>';
echo '<button type="submit" name="complete_item" formaction="todo.php" formmethod="POST">Complete Item</button>';
echo '<br>';
}
echo '<hr>';
}
?>
I was also got stuck on same kind of problem what I did was I tried to put the updating variables in ' ' single quotes.
If it can help you you can try this queries
$update = "UPDATE items SET item_owner='$currentID' WHERE item_id='$id'";
$update = "UPDATE items SET item_is_done='1' WHERE item_id ='$id'";
I'm not too familiar with PHP arrays, I have the following code that generates query to output the results needed.
$allstore = $_POST['store'];
function createSelect($allstore)
{
if (empty($allstore))
return "";
$querySelect = "";
$queryJoin = "";
$baseTable = "";
foreach ($allstore as $store => $value) {
if (!$querySelect) {
$baseTable = $store;
$querySelect = "SELECT " . $store . ".item_no, " . $store . ".actual_price, " . $store . ".selling_price, " . $store . ".qty as " . $store;
} else {
$querySelect .= ", " . $store . ".qty as " . $store;
$queryJoin .= "
INNER JOIN " . $store . " ON " . $baseTable . ".item_no = " . $store . ".item_no";
}
}
$querySelect .= " FROM " . $baseTable;
$query = $querySelect . $queryJoin;
return $query;
}
//Stores to be shown
$allstore = ['s_M9' =>0 , 's_M10' =>1];
$query = (createSelect($allstore));
$result = mysql_query($query);
//rest of code...
As you can see above, at the very top there is $allstore = $_POST['store']; Which collects values based from previous form POST method that has checkbox with the name=store[] .
Now According to the function shown, if I create my own keys and values like this
$allstore = ['s_M9' =>0 , 's_M10' =>1];
the output shows exactly what i'm looking for. But the problem goes on how to let $allstore implode those stores s_M9, s_M10 based on what the user has selected on the previous page ( checkbox )? I mean, the user can select either one of the stores or Both stores . How can I implode the checked results between those brackets without inserting them manually?
Thank You
Edit :
<?php
echo "<form action='somewhere.php' method='POST'>";
$query = "SELECT * from stores_list ORDER BY short Asc";
$result = mysql_query($query);
if(mysql_num_rows($result)>0){
$num = mysql_num_rows($result);
for($i=0;$i<$num;$i++){
$row = mysql_fetch_assoc($result);
echo "<input type=checkbox name=store[] value={$row['short']} style='width:20px; height:20px;'>{$row['short']}";
}
}
else{
//No Stores Available
echo "No Stores Found !";
}
echo "</td><input type='submit' value='Search'/></form>";
$allstore = [];
if (!empty($_POST['store'])) {
foreach ($_POST['store'] as $value) {
$allstore[$value] = 1; // or 0, it doesn't matter because your function adds all the keys
}
}
$query = (createSelect($allstore));
$result = mysql_query($query);
And of course you have to take care of your createSelect function to avoid SQL Injections, please read here
I'm comparing current data with updated data to check whether there are changes in information, and add the changes to a new table changes:
if (isset($_POST['submit']))
{
$sql = "SHOW COLUMNS FROM Employees";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)){
$tempname = $row['Field'];
$sql2 = "UPDATE Employees SET ".$row['Field']."= '$_POST[$tempname]' WHERE AFNumber='".$_GET["af"]."'";
$result2 = mysqli_query($con,$sql2);
if ($con->query($sql2) === TRUE) {
} else {
echo "Error: " . $sql2 . "<br>" . $con->error;
echo '<script>swal("Error", "Something went wrong '.$con->error.'", "error");</script>';
}
$sqlOldData = "SELECT * FROM Employees WHERE AFNumber='".$_GET["af"]."' AND (".$row['Field']." NOT LIKE '".$_POST[$tempname]."')";
$result3 = $con->query($sqlOldData);
if ($result3->num_rows > 0) {
while($row3 = $result3->fetch_assoc()) {
$sql3 = "INSERT INTO Changes (Table, AFNumber, Attribute,DateChanged,HRUser,OldValue,NewValue)
VALUES ('Employees', '".$_GET["af"]."', '".$row["Field"]."', '".date('dd/m/Y HH:mm:ss')."', '$login_session', '.$row3[0]', '$_POST[$tempname]')";
if ($con->query($sql3) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql3 . "<br>" . $con->error;
}
}
} else {
echo "0 results";
}
}
Now i want to extract information about the changes such as date user ... And put them in a textarea tag in this form:
<textarea name="changes" rows="50" cols="59" disabled>
12/07/2015 - User:"Mike" Changed:"Actual Location" From: "blabla" to "bla"
</textarea>
But I'm not sure how to do this, any help please...
Without knowing much about your data (for example what AFNumber is) I would suggest simply querying everything from the Changes table, and displaying them in the desired form:
$changes = $con->query("SELECT * FROM Changes WHERE Table = 'Employees'");
if ($changes->num_rows > 0) {
echo '<textarea name="changes" rows="50" cols="59" disabled>' . "\n";
while ($row = $changes->fetch_assoc()) {
echo sprintf('%s - User:%s Chnaged:"%s" From: "%s" to "%s"',
$row['DateChanged'], $row['HRUser'], $row['Attribute'],
$row['OldValue'], $row['NewValue']) . "\n";
}
echo "</textarea>";
}
To display the data I simply use echo here, but using some template system shouldn't make much difference to the core concept of the solution.
From your comment, you have the following code :
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
}
else
{
echo "0 results";
}
$conn->close();
To get the information into a text area in the way you are doing, use:
echo '<textarea name="changes" rows="50" cols="59" disabled>id:' . $row['id' . ' - Name: ' . $row['firstname'] . ' ' . $row['lastname'] . '</textarea>';