PHP Gallery CMS - Cannot Update Row in PHPMyadmin (LONG) - php

Project: Create a simple CMS for a photography website. My first project in php. :)
Problem: I am 90% finished with the CMS, but have ran into an issue of not being able to UPDATE row data after being READ from database.
The Goal: What I am trying to achieve seems simple. I have an admin page that reads image data from a database (id, image) and I am using a while loop to display this. It works great, and so does the delete button.
<?php
$query = "SELECT * FROM photos";
$select_all_photos_query = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($select_all_photos_query)) {
$photos_id = $row['photos_id'];
$photos_image = $row['photos_image'];
$photos_title = $row['photos_title'];
$photos_alt = $row['photos_alt'];
echo "<tr>
<td><input type='checkbox' name='photo' value='photo'></td>
<td><img src='../images/$photos_image' width='70'></td>
<td><a class='edit' href='edit_photo.php?&p_id={$photos_id}'>Edit</a></td>
<td><a onClick=\"javascript: return confirm('Are you sure?') \"class='delete' href='admin.php?delete={$photos_id}'>Delete</a></td>
</tr>";
}
?>
The problem I am having is the Edit Button in my while loop. I am using a get method in my href to get the edit_photo.php page with a parameter named "p_id" that is = to $photos_id.
Once I click the Edit button it sends me to the edit_photo.php page and I see all of the CORRECT information which tells me it is reading it correctly. I do get a error at the bottom ( Notice: Undefined variable: photos_file) See code below.
<?php
if (isset($_GET['p_id'])) {
$photo_id = $_GET['p_id'];
// Send query to photos table in database. //
$query = "SELECT * FROM photos WHERE photos_id = $photo_id";
$result = mysqli_query($connection, $query);
// Grab unique row from photos table in database. //
while($row = mysqli_fetch_assoc($result)) {
$photo_file = $row['photos_image'];
$photos_title = $row['photos_title'];
$photos_desc = $row['photos_alt'];
}
}
?>
Now. Here comes the big problem. When I try to update this information, the program busts. I even checked to see if my sql is correct, and if the queries are connecting to database. See code below.
<?php
if (isset($_POST['image'])) {
// After "Save" is pressed, the values white space is trimmed and assigned to a variable. //
$photos_title = trim($_POST['photos-title']);
$photos_desc = trim($_POST['photos-description']);
$photos_file = $_FILES['image']['name'];
$photos_file_temp = $_FILES['image']['name_tmp'];
// The new variables are sanitized. //
$photos_title = mysqli_real_escape_string($connection, $photos_title);
$photos_desc = mysqli_real_escape_string($connection, $photos_desc);
}
// Send the Update query to the database. //
$update_query = " UPDATE photos SET
photos_image = '$photos_file', photos_title = '$photos_title', photos_alt = '$photos_desc'
WHERE photos_id = '$photo_id' ";
// Test the SQL syntax. //
if(!$update_query) {
echo "Wrong." . " " . mysqli_error($connection);
}
else { echo "The SQL appears right..." . "<br>";
}
// Test the Update query. //
$update_result = mysqli_query($connection, $update_query);
if(!$update_result) {
echo "Didnt Connect." . " " . mysqli_error($connection);
} else {
echo "Sent query to to database.";
}
?>
<form action="edit_photo.php" class="settings-form" method="post" enctype="multipart/form-data">
<div class="form-group edit-preview">
<label for="image">Photo</label>
<img src= <?php echo "../images/$photo_file"?> >
<input type="file" name="file_upload">
</div>
<div class="form-group">
<label for="photos-title">Title</label>
<input type="text" name="photos-title" value= <?php echo "$photos_title" ?> class="form-control">
</div>
<div class="form-group">
<label for="photos-description">Description</label>
<textarea type="text" rows="4" name="photos-description" class="form-control" ><?php echo "$photos_desc" ?> </textarea>
</div>
<div class="form-group">
<input type="submit" name="image" class="btn btn-primary" value="Save Photo">
</div>
</form>
I have spent four days trying to figure this out with no luck.

For one thing, it's failing because of this ['name_tmp'].
The syntax is ['tmp_name'] - you had those inversed
Ref: http://php.net/manual/en/features.file-upload.php so your temp file never gets processed.
Then as per your edit and seeing your HTML form:
You're using name="file_upload" and then using the $_FILES['image'] array; those names need to match.
Error reporting would have helped you here.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Additional note.
If you are attempting to set the given (file) column as binary data instead of the path to the given file(s) as text, then you MUST escape it.
Otherwise, MySQL will throw you an error.
If that is the case, you will need to do the same as the others:
$photos_file = $_FILES['file_upload']['name']; // notice I changed it to what it should be
$photos_file = mysqli_real_escape_string($connection, $photos_file);
as per <input type="file" name="file_upload">
Check for errors against all your queries; you're not doing that in your $query = "SELECT * FROM photos WHERE photos_id = $photo_id"; query.
Add or die(mysqli_error($connection)) to all mysqli_query() should there be an error somewhere.
HTML stickler.
<textarea type="text" - <textarea> does not have a "text" type; remove it.
Footnotes.
If you want to check if your UPDATE truly was successful, use mysqli_affected_rows().
http://php.net/manual/en/mysqli.affected-rows.php
Instead of else { echo "The SQL appears right..." . "<br>"; }
As outlined in comments, your code is open an SQL injection.
If $photo_id is an integer, change
$photo_id = $_GET['p_id'];
to
$photo_id = (int)$_GET['p_id'];
However, if that is a string, then you will need to quote it and escape it in your query.

Related

PHP and MYSQLI Check if user ID is present and if not create it

I have been looking for 3 weeks on the Internet for an answer to this question and cannot find anything that even comes close or in handy. I have a Database Table that i need to have checked. If a Users_ID is present in that table, I would like my code to display an update.php link in my form action="" tag and if the Users_ID is not present in that db table, then i would like to have an Insertdb.php page to be linked in the form instead of an update.php page. Here is what I have:
PHP Code:
<?php
session_start();
error_reporting(E_ALL);
include_once("dbconnect.php");
$users_id = $_SESSION['user_id'];
$sql = "SELECT * FROM dbtable WHERE uid=$users_id";
if($results = $con->query($sql)) {
while($display = $results->fetch_array(MYSQLI_ASSOC)) {
$uid = $display['uid'];
if($display['uid']==""){
$pagelink = "insertintodb.php";
}else{
$pagelink = "updatedb.php";
}
}
$results->close();
}
?>
And my HTML section looks like this:
HTML Code:
<form action="<?php echo $pagelink; ?>" method="POST">
<input type="text" value="" placeholder="Insert Value" name="something" />
<input type="submit" value="Submit Data" name="submit_data_to_db" />
</form>
How would I go about doing this? My current method Posted above is what I'm currently using, however its displaying only <form action="" method="POST"> when i check it against the pages view-source. Please help me anyway you can. Any and all help would be greatly appreciated. Thank you
you usually use num_rows method:
<?php
session_start();
error_reporting(E_ALL);
include_once("dbconnect.php");
$users_id = $_SESSION['user_id'];
$sql = "SELECT * FROM dbtable WHERE uid=$users_id";
if($results = $con->query($sql)) {
if($results->num_rows() > 0){
$pagelink = "insertintodb.php";
}else{
$pagelink = "updatedb.php";
}
}
$results->close();
}
?>
I see you use $con but I see nowhere you have declared it.
Can you confirm that actually exists? It is possible your script is halting its execution at that point.
Also a few things I would implement in there:
1. When you use variables that come from external sources (like your forms), or even other variables really, always care for SQL injection;
2. Your if & else can be reduced to just an if (when you find an ID). To all others case, you wish a default behaviour that is your else. So something like this:
$pageLink = "insertintodb.php";
if (!empty($display['uid'])) {
$pageLink = "updatedb.php"
}

Run two completely different sqli queries inside one script

I'm new to php.
I have this page:
<?php
function renderForm($id, $StaffFullName, $StaffJobPosition, $error)
{
?>
<!doctype html>
<html>
<head><title></title></head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div>'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p>ID: <?php echo $id; ?></p>
Name: * <input type="text" name="StaffFullName" value="<?php echo $StaffFullName; ?>"/><br/>
Job Position: * <select name="JobPosition">
<?php
$query = "SELECT * FROM LUT_JOBPOS";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)){
if ($StaffJobPosition == $row['JobposID'])
{
echo "<option value='{$row['JobposID']}' selected='selected'>{$row['JobposTitle']}</option>";
}
else {
echo "<option value='{$row['JobposID']}'>{$row['JobposTitle']}</option>";
}
}
$result->close();
?>
</select><br/>
<input type="submit" name="submit" value="Update">
<input type="button" onClick="parent.location='view.php'" value="Back">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
require_once('../../authenticate.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// do some funky stuff
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checking that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$query = "SELECT * FROM STAFF WHERE StaffID=$id";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);
$result->close();
// check that the 'id' matches up with a row in the database
if($row)
{
// get data
$StaffFullName = $row['StaffFullName'];
$StaffJobPosition = $row['StaffJobPosition'];
// show form
renderForm($id, $StaffFullName, $StaffJobPosition, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
So, what happens here is this:
When you open the page like edit.php?id=1, it fetches the data of the associated record from STAFF table and shows them on page for the user to edit them.
This part of the code works fine.
I also want the user to be able to select "Job Position" possible values from a drop down box. The drop down box should get its data from another table in database, LUT_JOBPOS.
This is the part of the code that doesn't work.
I was using mysql_query commands before on this page and it worked perfectly. However I was told to switch on mysqli_query instead.
Since I did the conversion I can't find how to run these two queries on the same script.
I messed a little bit with the require_once command and depending on where I call it I can run one query or another, but never both of them.
Looking at the logs of my web host the only thing I can see that may be relevant to my issue is:
"mod_fcgid: stderr: PHP Notice: Undefined variable: connection in /var/www/vhosts/myhostdomain.com/httpdocs/prod15/admin/staff/edit.php on line 24"
The connection variable comes from authenticate.php and it holds the connection parameters to the database. I'm sure it's set otherwise the first query (that gets the user data) wouldn't work.
I read somewhere that you can't run two sqli queries on the same script.
Then how I'm supposed to use a LUT table (lookup table)?
PS: I know that for showing the data I can use a UNION and that's what I do.
But when I edit the data I want the user to be able to select only from the possible values that exist on the LUT table (drop down select box)
Any help?
You have a lot of issues in your code. You really need to review it before use it in some real application, but for your specific problem, here is my guess.
You are calling the line $result = mysqli_query($connection, $query); in the line 24 and only after taht you call require_once('../../authenticate.php');.
As you said, the $connection var is defined in the authenticate.php, so in the line 24 is undefined.
Try to use require in the first line of your php script.

Set amounts in database using php + form

In my database users have a balance, im trying to set up a form that allows them to transfer amounts to each other. So for the from user it would - out of their current balance and update it to the new balance ( existing - amount transferred ) and for the receiver it would update ( existing + amount received ).
Heres my code below but its not updating any of the information:
<?php
if (isset($_POST['submit'])) {
$fromuser = $_POST['fromuser'];
$touser = $_POST['touser'];
$amount = $_POST['amount'];
$balanceto = mysql_query("SELECT `money` FROM `users` WHERE username = '$touser'");
$res1 = mysql_fetch_array($balanceto);
$balancefrom = mysql_query("SELECT `money` FROM `users` WHERE username = '$fromuser'");
$res2 = mysql_fetch_array($balancefrom);
$newmoney1 = ($res1['money'] + $_POST['amount']);
$newmoney2 = ($res2['money'] - $_POST['amount']);
$result1 = mysql_query("UPDATE `users` SET `money`='$newmoney1' WHERE username = '$touser'");
$result2 = mysql_query("UPDATE `users` SET `money`='$newmoney2' WHERE username = '$fromuser'");
}
?>
<form class="reg-page" role="form" action="" method="post">
<center>
Please note: Transfering funds is done at your own risk, please make sure you transfer the funds to the right person.<br><br>
<?php
$query = "SELECT username FROM users";
$result = mysql_query($query) or die(mysql_error());
$dropdown = "<div class='row'><div class='col-sm-6'><label>Transfer $ To<span class='color-red'> *</span></label><select name='touser' class='form-control margin-bottom-20'>";
while($row = mysql_fetch_assoc($result)) {
$dropdown .= "\r\n<option value='{$row['username']}'>{$row['username']}</option>";
}
$dropdown .= "\r\n</select></div><div class='col-sm-6'>
<label>Amount $<span class='color-red'> *</span></label>
<input type='text' name='amount' class='form-control margin-bottom-20'>
</div></div>";
echo $dropdown;
?>
<input type="hidden" value="<?php echo $user_data['username']; ?>" name="fromuser">
<button type="submit" class="btn-u">Transfer</button>
</center>
</form>
All help much appreciated.
$_POST does not contain submit because you never put a NAME tag on the submit button.
Instead of:
<button type="submit" class="btn-u">Transfer</button>
You need:
<button type="submit" class="btn-u" name="submit">Transfer</button>
See here:
How do I post button value to PHP?
On further reflection it's probably a good idea to talk about some of the problems here, let's start with this one:
$balanceto = mysql_query("SELECT `money` FROM `users` WHERE username = '$touser'");
$res1 = mysql_fetch_array($balanceto);
$balancefrom = mysql_query("SELECT `money` FROM `users` WHERE username = '$fromuser'");
$res2 = mysql_fetch_array($balancefrom);
This is duplicated code, you can move this into a function to avoid copying and pasting, which is good practice, and you can use that function in other places in your code when you need to get the balance. Formatting the structure correctly helps in the event that your table changes, and you need to update the SQL. Without this in a single place, you are going to climb all over your code to find all the changes and update them.
<input type="hidden" value="<?php echo $user_data['username']; ?>" name="fromuser">
This is very bad practice, as it makes it easy for someone to slip an extra variable into the header and submit whatever user they want to your code, transferring money out of any other account that they want. Since this page already has access to this variable:
$user_data['username']
You should be using this in the IF statement at the top, instead of submitting it along with the form.
<input type='text' name='amount' class='form-control margin-bottom-20'>
This is another problem. You are asking for an amount, but creating a text field. A better example of this would be:
<input type='number' name='amount' class='form-control margin-bottom-20'>
Again though, these are easily modifiable post values, you have to make sure to check again on the server to make sure you didn't get fooled:
if(!(isNumeric($_POST['amount']) || $_POST['amount'] == 0 || $_POST['amount'] == ''))
The code above checks to make sure you have a numeric value, and that it is not 0 or blank, both of which would be invalid inputs. If either of those values is submitted, then it errors out and sends the user back to the form without processing the update.
Later on in your code, you start a PHP Tag to create the drop down:
<?php
$query = "SELECT username FROM users";
$result = mysql_query($query) or die(mysql_error());
$dropdown = "<div class='row'><div class='col-sm-6'><label>Transfer $ To<span class='color-red'> *</span></label><select name='touser' class='form-control margin-bottom-20'>";
Assigning all of this to the $dropdown variable is completely wasted if you aren't going to use that drop down again (and it seems you are not). I can see that you wrapped it in PHP so you can loop over the options to print them out, but you can do that just as easily with a smaller PHP tag with a loop inside it, like this:
<select name='touser' class='form-control margin-bottom-20'>
<option value="null">Not Selected</option>
<?php
// Loop over all our usernames...
while($row = mysql_fetch_assoc($result)) {
// If we're not the current user...
if($row['username'] != $user_data['username']) {
// Add a drop down option!
echo "<option value='" . $row['username'] . "'>" . $row['username'] . "</option>";
}
}
?>
</select>
Note that this option ALSO includes a default "null" value for the select menu, and filters out the existing user (you can't transfer money to yourself, at least in this example). The null value is necessary because without it your code would automatically select the first user on the drop down list.
This would be my implementation of the same set of code here:
<?php
// If our submit is set...
if (isset($_POST['submit'])) {
// Get the balance for the from user
$fromBalance = getBalance($user_data['username']);
// Get the balance for the to user
$toBalance = getBalance($_POST['touser']);
// Get our new amounts, but don't do anything yet!
$newmoney1 = $toBalance + $_POST['amount'];
$newmoney2 = $fromBalance - $_POST['amount'];
// Check to make sure we have a valid amount
if(!(isNumeric($_POST['amount']) || $_POST['amount'] == 0 || $_POST['amount'] == '')) {
// Or error out!
echo 'ERROR: Bad amount Specified!';
// Check to make sure we have two valid users
} elseif($user_data['username'] == $_POST['touser']) {
// Or error out!
echo 'ERROR: Cannot transfer money to yourself!';
// Check to make sure sufficient funds are available
} elseif($newmoney2 < 0) {
// Or error out!
echo 'ERROR: Insufficient funds!';
// Check for default user selection...
} elseif($_POST['touser'] === 'null') {
// Or Error Out
echo 'ERROR: No username selected!';
// Otherwise we are good...
} else {
// So we call our update functions.
updateMoney($user_data['username'], $newmoney2);
updateMoney($_POST['touser'], $newmoney1);
// Send a success message
echo 'Transfer completed successfully, thank you!<br /><br />';
}
}
/** updateMoney()
*
* This function will take a user name and an amount and update their balance.
* Created to re-use code instead of copy and paste.
*
* #arg $user string
* #arg $amount integer
*/
function updateMoney($user, $amount) {
// Update our database table for this user with this amount
$result1 = mysql_query("UPDATE `users` SET `money`='$amount' WHERE username = '$user'");
}
/** getBalance()
*
* This function will return a balance for a given username.
* Created to re-use code instead of copy and paste.
*
* #arg $user string
* #return $amount integer
*/
function getBalance($user) {
// Execute query to get the result
$result1 = mysql_query("UPDATE `users` SET `money`='$amount' WHERE username = '$user'");
// Assign the result to a value
$res1 = mysql_fetch_array($balanceto);
// Return only the value we care about
return $res1['money'];
}
// Set our query for getting usernames from the DB
$query = "SELECT username FROM users";
// Get the usernames!
$result = mysql_query($query) or die(mysql_error());
?>
<form class="reg-page" role="form" action="" method="post">
<center>
Please note: Transfering funds is done at your own risk, please make sure you transfer the funds to the right person.
<br>
<br>
<div class='row'>
<div class='col-sm-6'>
<label>Transfer $ To<span class='color-red'> *</span></label>
<select name='touser' class='form-control margin-bottom-20'>
<option value="null">Not Selected</option>
<?php
// Loop over all our usernames...
while($row = mysql_fetch_assoc($result)) {
// If we're not the current user...
if($row['username'] != $user_data['username']) {
// Add a drop down option!
echo "<option value='" . $row['username'] . "'>" . $row['username'] . "</option>";
}
}
?>
</select>
</div>
<div class='col-sm-6'>
<label>Amount $<span class='color-red'> *</span></label>
<input type='number' name='amount' class='form-control margin-bottom-20'>
</div>
</div>
<button type="submit" class="btn-u" name="submit">Transfer</button>
</center>
</form>
But you STILL need to go fix the code so that you are NOT using MySQL and switch to MySQLi or PDO so that you can do prepared statements and actually protect yourself from MySQL injection attacks.
See here for more details:
https://wikis.oracle.com/display/mysql/Converting+to+MySQLi
You have posting the form with nameless button and trying to access via $_POST['submit']
<button type="submit" class="btn-u">Transfer</button>
name is missing. Add and try
<button type="submit" name="submit" class="btn-u">Transfer</button>
I think the button is missing tag 'name'. Try add this on your button:
<button type="submit" class="btn-u" name='submit'>Transfer</button>
To optimize your script I suggest do this:
if (isset($_POST['submit'])) {
$fromuser = $_POST['fromuser'];
$touser = $_POST['touser'];
$amount = $_POST['amount'];
$result1 = mysql_query("UPDATE `users` SET `money`= `money` + '$amount' WHERE username = '$touser'");
$result2 = mysql_query("UPDATE `users` SET `money`= `money` - '$amount' WHERE username = '$fromuser'");
}
So, you will eliminate two steps of processing and two hits on database.
start transaction
INSERT INTO power (sender, receiver, amount) VALUES ('$sender', '$receiver', '$amount')
UPDATE users SET power=power-$amount WHERE user_id='$sender'
UPDATE users SET power=power+$amount WHERE user_id='$receiver'
Submit button missing the name tag. use Transfer
Nothing glaringly wrong with the code, I'm assuming this is fake money.
Probably a malformed sql statement, try echoing the attempted sql before hand.
make sure all the queries work for a test example.

GET POST mysql data on next page

Ok, I haven't done much of this sort of stuff, so I am clueless right now.
On the first page you hit the form submit that generates a bunch of information/stuff and displays it underneath submit button, but I don't know how to take the displayed information and use it on the next page I will show some of my code. btw I know the code is bad, just ignore that fact.
<form name="input" action="slaymonster.php" method="post" id="id">
<div align="center">
<input name="Submit" id="Submit" type="submit" class="button" value="Explore Map!"/>
</div>
</form>
if (isset($_POST['Submit'])) {
include 'includes/mapstuff.php';
// So here we pick a random row from the table pokemon notice the order by rand
$sql23 = "SELECT * FROM map1pokemon ORDER BY RAND() LIMIT 1;";
// We then check for errors
$result23 = mysql_query($sql23) or die(mysql_error());
// we then make the result into a virable called battle_get23
$battle_get23 = mysql_fetch_array($result23);
$sql2 = "SELECT * FROM pokemon WHERE name='".$battle_get23['pokemon']."'";
$result2 = mysql_query($sql2) or die(mysql_error());
$battle_get2 = mysql_fetch_array($result2);
// Now we need to make sure the image is safe be for we use it
$pic2= mysql_real_escape_string($battle_get2['pic']);
$pic = strip_tags($pic2);
include 'includes/maptypes.php';
?>
<form name="inputt" action="" method="post">
<div align="center">
<input type="submit" class="catch" value="Catch Pokemon" name="catch">
</div>
</form>
<p></p>
<?php
echo "You have just found a " ;
echo $randomview97[0];
echo " ";
echo $battle_get23['pokemon'];
$_SESSION['pokemon'] = $battle_get23['pokemon'];
$_SESSION['type'] = $randomview97[0];
$_SESSION['pic'] = $battle_get2;
$_SESSION['money'] = $randomview2[0];
$_SESSION['level'] = $randomview3[0];
$_SESSION['ticket'] = $randomview4;
?>
<p></p>
<?php
echo "You have gained ".$randomview3[0]." levels" ;
echo " ";
?>
<p></p>
<?php
echo "You have received $".$randomview2[0]."" ;
echo " ";
?>
<p></p>
<?php
echo "</center>";
}
?>
it displays the pokemon's picture it's name, type,amount of money you got ect...
I need all that information to be useable on the next page.
Any help is appreciated :)
At the top of your PHP code, be sure to include session_start();
You are already using session variables, so you should refer here to see what a PHP session is: PHP session_start() - Manual. It makes sure to do exactly what you are asking for (someone may point out that in certain cases session_start(); is not necessary, but for your purposes, while learning, stick to the Manual for best practices)
This information will be usable on the next 'page', just as the manual describes, and will be available, until you call something like session_destroy().
If you want to pass the information from one page to another. You have to put the result inside the form tag. Then it is possible to pass the information to another page. Or you can put it on the session and get information from any page.
you got my point? If you explain what you want to do. Then I will do something for you.

php & mysql query - cannot return the variable I need from MySQL

update: There must be a minor syntax error in some accompanying validation for $_GET variable. I rewrote everything carefully and the script now works. Thank you all!
I've spent more than 5 hours trying to find what's wrong with my code.
1st page: a db query retrieves some vimeo videos from the db and presents each one of them with an "edit" link which dynamically gets the video's id (vimeo 8-digit id). To do this, I just call the following function:
function edit_portfolio_videos() {
global $connection;
$query = "SELECT * FROM portfolio_videos ORDER BY video_id ASC";
$portfolio_videos_set = mysql_query($query, $connection);
confirm_query($portfolio_videos_set);
while ($portfolio_video = mysql_fetch_array($portfolio_videos_set)) {
echo "<iframe src=\"http://player.vimeo.com/video/";
echo $portfolio_video['video_code'];
echo "?title=0&byline=0&portrait=0&color=ffffff\" width=\"400\" height=\"230\" frameborder=\"0\" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe><br />";
echo "Edit this Video";
}
}
2nd page: This is the page where each video will be edited by the administrator. Example URL would be something like "http://www.my_website.com/edit_portfolio_video.php?videocode=34956540". On this page, I use the following function to get the array from the previous page's script:
function get_selected_video_by_id($video_code) {
global $connection;
$query = "SELECT * FROM portfolio_videos ";
$query .= "WHERE video_code = '$video_code' ";
$query .= "LIMIT 1";
$videos_set = mysql_query($query, $connection);
confirm_query($videos_set);
if ($video = mysql_fetch_array($videos_set)) {
return $video;
} else { $video = NULL; }
}
and then...
$selected_video = get_selected_video_by_id($_GET['videocode']);
in order to put every kind of data related to the selected video in the edit form:
<form action="edit_portfolio_video.php?videoid=<?php echo $selected_video['video_code']; ?>" method="post">
<input type="text" name="video_title" value="<?php echo $selected_video['video_title']; ?>" />
</p>
<p>Video Code (vimeo):<br />
<input type="text" name="video_code" value="<?php echo $selected_video['video_code']; ?>" />
</p>
<p>Video Description:<br/>
<textarea name="video_description" rows="5" cols="70"><?php echo $selected_video['video_description']; ?></textarea>
</p>
<p>
<input type="submit" name="submit" value="Save Video" />
</p>
</form>
But the form's fields don't get populated, as there seems to be a problem with the $video variable I'm trying to get (returned from get_selected_video_by_id function). The video code is stored as "INT" (length: 11) in the database and is printed as string in the 2nd page's URL. I've tried to write the function's query in many ways but I can't get it to work.
I'd appreciate some help on this, thank you all.
Note: The confirm_query function does this simple job:
function confirm_query($result_set) {
if (!$result_set) {
die("Database query failed: " . mysql_error());
}
}
I think you should try this instead for your get_selected_video_by_id SQL query.
$query = "SELECT * FROM portfolio_videos WHERE video_code = ".$video_code;
Of course watch out for SQL injection in your parameters, and also, as someone already suggested please consider using PDO or MySQLi.
Your Form seems strange:
you are using a POST mode to pass a GET value (edit_portfolio_video.php?videoid=...etc...).
But this shouldn't be the problem.
In this line:
$selected_video = get_selected_video_by_id($_GET['videocode']);
are you sure the GET parameter you are passing is videocode? Or is it videoid?

Categories