Okay so I'm making php that will pull every entry from a data base that matches the name you put in a textbox. so here is a image of the database
http://i.stack.imgur.com/LvmrM.png < screen shot of database
So if i where to put "DigitalNuke" in the textbox and hit the submit button I want only the rows that have "DigitalNuke" as the value in the second column "referrer"
<form ACTION="" METHOD=post>
<div class="input-append">
<input class="span2" id="youruser" type="text" name="youruser" placeholder="Your Username">
<button class="btn btn-success" type="submit">Retrive</button>
</div>
</form>
<?php
require_once 'connect.php';
$name = isset($_POST['youruser']);
$conn= mysqli_connect ($dbhost,$dbuser,$dbpass,$dbname)or die(mysqli_error());
$query1 = "SELECT 'id', 'referrer', 'username', 'brigade', 'faction', 'activity' FROM refmems WHERE referrer='$name";
$result = mysqli_query($conn, $query1)
or die('Error querying the database: ');
echo '<table class="table table-bordered">';
echo '<caption>Your Referred Members</caption>' . '<thead><tr><th>ID</th>' . '<th>Username</th>' . '<th>Brigade</th>' . '<th>Faction</th>' . '<th>Activity</th>' . '</tr></thead>';
while ($row = mysqli_fetch_array($result)) {
echo "<tr class='success'><td>" . $row['id'] . "</td><td>" . $row['username'] . "</td><td>" . $row['brigade'] . "</td><td>" . $row['faction'] . "</td><td>" . $row['activity'] ."</td></tr>";
}
?>
So as of now it doesn't do anything when I hit the submit button. Well it kind of works, except for instead of pulling the data from the table, it just puts id, username, brigade, faction, activity in each row of the generated table.
http://i.stack.imgur.com/XF71h.png < screen shot
Any help would be appreciated, if you need anything else let me know and i'll post it.
$query1 = "SELECT 'id', 'referrer', 'username', 'brigade', 'faction', 'activity' FROM refmems WHERE referrer='$name";
should be:
$query1 = "SELECT `id`, `referrer`, `username`, `brigade`, `faction`, `activity` FROM refmems WHERE referrer='$name'";
Also learn how to use prepared statements for MySQLi. Your code is open to SQL injection.
Your syntax is broken.
"SELECT id, referrer, username, brigade, faction, activity FROM refmems WHERE referrer='$name"
There is no closing single quote after $name, and the fields don't get quoted (or use backticks but it isn't necessary).
Also, you are asking for trouble. You've got user input with no validation/sanitization.
Related
I have a page that I have been working on. It runs several queries to get existing data from several tables in my DB. There is a table that shows the result of three queries. The first query gets the extension and the secret of phones, the 2nd query gets MAC addresses of phones, and finally the third query gets the names of templates for the phones. The results of the last two queries (with the help of others) are setup as dropdowns in the 3rd and 4th columns of the table created to show the extensions. This way I can select the MAC of the phone I want to assign to the extension and then the template to make the phone work the way I want. The whole page is set as a form and I am using $post to the insert page. My goal here is to take the information (array) that is created by the user making their selections and insert ALL the 4 columns of information into a new table, from there I want to create files using that information to setup the phones. Here is the code I have for now.
<?php
error_reporting(E_ALL);
ini_set('display_errors','On');
$link = mysql_connect("localhost", "root", "cacti") or die ('Error connecting to mysql' . mysql_error());
mysql_select_db("cqadmin");
$sql2 = "SELECT extension, secret from extensions;";
$result2 = mysql_query($sql2) or die(mysql_error());
echo "<table border='3'>
<tr>
<th>Extension #</th>
<th>Secret</th>
<th>MAC Address</th>
<th>Template</th>
</tr>";
while($row = mysql_fetch_array($result2))
{
$sql = "SELECT id , mac FROM phones order by mac;";
$result = mysql_query($sql) or die(mysql_error());
$sql1 = "SELECT id , templatename FROM templates order by templatename;";
$result1 = mysql_query($sql1) or die(mysql_error());
echo "<tr>";
echo "<td>" . $row['extension'] . "</td>";
echo "<td>" . $row['secret'] . "</td>";
echo "<td> <select name='phone'>";
while($rowA = mysql_fetch_array($result)) {
echo '<option value="' . $rowA['id'] . '">' . $rowA['mac'] . '</option>';
}
echo "</select></td>";
echo "<td><select name='template'>";
while($rowB = mysql_fetch_array($result1)) {
echo '<option value="' . $rowB['id'] . '">' . $rowB['templatename'] . '</option>';
}
echo "</select></td>";
echo "</tr>";
}
echo "</table>";
?>
<input type="submit" value="Submit your selections">
</body>
</html>
And my insert page
<?php
echo "You got here";
//***********Get the Assignment information *************
$values = array_values($_POST);
print_r($values);
?>
The resulting print shows this
Array ( [0] => 324 [1] => 24 )
Looking at my db table 324 is the index id of the last phone scanned and in the template table 24 is the last template created, No info on the extension or the secret.
I think I am close but I do not know where to go from here.
PS. I know I need to use mysqli or pdo, not sure how to change over yet.
I am a beginner in PHP.I am stuck with a problem. The idea is that I have to assign actors to a selected movie and add a role for each. I need to pick several values from the list and add a description for each via texfields. My code adds all the checked values to the database, but it makes a mess with the values from the textfields, the checked values don't match with the description. I would be really grateful for your help!
My code:
Form:
<?php
$sqlquery = "SELECT artistId, firstname, lastname from $artists order by 2";
$result = mysqli_query($connect, $sqlquery);
if($result) {
echo "<table class=\"addactor\">";
echo "<tr>
<td id=\"text\" colspan=\"2\"><h3>Assign an actor to the movie</h3></td>
</tr>";
while($sqlRow = mysqli_fetch_array($result, MYSQL_ASSOC)) {
echo "<tr>";
echo "<td>";
echo "<input type=\"checkbox\" name=\"checkbox[]\" value=\"" . $sqlRow['artistId'] . "\"/> " . $sqlRow['firstname'] . " " . $sqlRow['lastname'] . "</td><td><input type=\"text\" name=\"textbox[]\"/></td>";
echo "</tr>";
}
echo "<tr><td align=\"right\"><input type=\"submit\" name=\"submit\" id=\"submit\" value=\"Add\"></td><td><input type=\"reset\" name=\"reset\" id=\"reset\" value=\"Reset\"></td></tr></table>;";
}
print '</table>';
The connection to the database is in another file, which is included here.
The second part:
if($_POST) {
$checkbox = $_POST['checkbox'];
$txt = $_POST['textbox'];
$len = sizeof($checkbox);
for($i = 0; $i < $len; $i++) {
$sqlqr = "INSERT INTO $role (artistId, movieCode, Description) VALUES ('" . $checkbox[$i] . "', '" . $_POST['moviecode'] . "', '" . $txt[$i] . "')";
mysqli_query($connect, $sqlqr);
}
$query = "INSERT INTO $movies(movieCode, title, dateOfIssue,category, description, image) VALUES ('" . $_POST['moviecode'] . "', '" . $_POST['title'] . "', '" . $_POST['dateofissue'] . "','" . $_POST['category'] . "', '" . $_POST['desc'] . "', '" . $_POST['image1'] . "')";
mysqli_query($connect, $query);
if(mysqli_query($connect, $query) || mysqli_query($connect, $sqlqr)) {
echo "<h4>1 record added</h4>";
}
else {
die('Error: ' . mysqli_error($connect));
}
print '</form>';
}
Unchecked values are not submitted and checkbox quantity not same with textbox.
You should give input name array same keys :
$i = 0;
while($sqlRow = mysqli_fetch_array($result, MYSQL_ASSOC)) {
echo "<tr>";
echo "<td>";
echo "<input type=\"checkbox\" name=\"checkbox[".$i."]\" value=\"" . $sqlRow['artistId'] . "\"/> " . $sqlRow['firstname'] . " " . $sqlRow['lastname'] . "</td><td><input type=\"text\" name=\"textbox[".$i."]\"/></td>";
echo "</tr>";
$i++;
}
Use also this code:
$checkbox = $_POST['checkbox'];
$txt = $_POST['textbox'];
foreach ($checkbox as $key => $value)
$sqlqr = "INSERT INTO $role (artistId, movieCode, Description) VALUES ('" . $value . "', '" . $_POST['moviecode'] . "', '" . $txt[$key] . "')";
mysqli_query($connect, $sqlqr);
}
use mysql_escape_string($_POST['']) instead of the every field $_POST[''] in inside the mysqlquery.
As documented under 17.2.1 Control types:
When a form is submitted, only "on" checkbox controls can become successful.
In other words, the browser will only submit those checkbox controls that have been 'checked', yet will submit every textbox control irrespective of the status of the checkbox control with which you intended it to be associated.
Therefore, unless all checkbox controls were checked, the arrays $_POST['checkbox'] and $_POST['textbox'] created by PHP from the form submission will contain different numbers of elements—and, consequently, those with any given index may not match.
There are two ways of resolving this:
one can use client-side scripting to disable the textbox if the corresponding checkbox is unchecked: this will prevent the browser from submitting the textbox and, accordingly, the arrays in PHP will be aligned again (however note that this solution depends upon the availability of client-side script—you will have to test for and handle cases where such scripting is unavailable); or
one can give the controls explicit indexes to ensure that they are always aligned.
You also really ought to read up on proper string escaping (and how failure to do so exposes your application both to bugs and commonly exploited attack vectors): I thoroughly recommend #deceze's blog article, The Great Escapism (Or: What You Need To Know To Work With Text Within Text).
In particular, as he describes in his article, you should ensure that you escape any HTML in your variables before transmission to the browser (in order to prevent XSS attacks and bugs where the text to be output contains characters that have special meaning in HTML, for example <):
$result = mysqli_query($connect, "
SELECT artistId, CONCAT(firstname, ' ', lastname) AS fullname
FROM $artists
ORDER BY firstname
");
if ($result) {
echo '
<table class="addactor">
<tr>
<td id="text" colspan="2"><h3>Assign an actor to the movie</h3></td>
</tr>';
$i = 0;
while ($sqlRow = mysqli_fetch_array($result, MYSQL_ASSOC)) {
echo '
<tr>
<td>
<input type="checkbox"
name="checkbox[',$i,']"
value="', htmlentities($sqlRow['artistId']), '"
/>', htmlentities($sqlRow['fullname']), '
</td><td>
<input type="text" name="textbox[',$i,']"/>
</td>
</tr>';
$i++;
}
echo '
<tr>
<td align="right">
<input type="submit" name="submit" id="submit" value="Add">
</td><td>
<input type="reset" name="reset" id="reset" value="Reset">
</td>
</tr>
</table>';
}
Also, concatenating unescaped strings supplied by the user directly into your SQL not only makes you vulnerable to SQL injection attack, but furthermore introduces bugs where the strings contain characters that have special meaning within SQL string literals (for example ').
The solution is to prepare SQL statements with placeholders for parameters that get subsituted with your variables upon command execution; this also provides a performance boost since the statements need only be prepared once irrespective of the number of times that they are executed:
if ($_POST) {
$stmt = mysqli_prepare($connect, "
INSERT INTO $movies
(movieCode, title, dateOfIssue, category, description, image)
VALUES
(?, ?, ?, ?, ?, ?)
");
mysqli_stmt_bind_param($stmt, 'ssssss',
$_POST['moviecode'],
$_POST['title'],
$_POST['dateofissue'],
$_POST['category'],
$_POST['desc'],
$_POST['image1']
);
mysqli_execute($stmt) or die('Error: ' . mysqli_error($connect));
$stmt = mysqli_prepare($connect, "
INSERT INTO $role
(artistId, movieCode, Description)
VALUES
(?, ?, ?)
");
mysqli_stmt_bind_param($stmt, 'sss',
$checkbox,
$_POST['moviecode'],
$description
);
foreach ($_POST['checkbox'] as $i => $checkbox) {
$description = $_POST['textbox' ][$i];
mysqli_execute($stmt) or die('Error: ' . mysqli_error($connect));
}
echo '<h4>1 record added</h4></form>';
}
I've updated the code but keep getting new errors.
I'm really hoping that someone can help me and look at my code to see what is wrong.
I have a database table on a webpage and I have one edit button and one delete button on each table row. At the moment I'm just trying to get the delete button to work and it will just not delete the row in the database even though I selected that ID. It looks like it's picking up the correct ID.
Can someone tell what is wrong? Below is the code...
<?php
require 'connect.inc.php';
if (isset($_POST['delete']) && isset($_POST['id'])) {
$id = get_post('id');
$query = "DELETE FROM movies WHERE id='.$id.' LIMIT 1";
if (!mysql_query($query, $db_server))
echo "DELETE failed: $query<br>".
mysql_error() . "<br><br>";
}
$query = "SELECT * FROM movies, categories WHERE movies.genre_id = categories.genre_id";
$result = mysql_query($query);
if (!$result) die ("Database access failed:" .mysql_error()) ;
$rows = mysql_num_rows($result);
echo '<table><tr><th>Title</th><th>Release year</th><th>Genre</th><th>Director</th><th>Update</th><th>Delete</th></tr>';
for ($j = 0 ; $j < $rows ; ++$j) {
$row = mysql_fetch_row($result);
//$id = $row[0];
echo '<tr><td>' .$row[1] . '</td>' ;
echo '<td>' .$row[2] . '</td>' ;
echo '<td>' .$row[3] . '</td>' ;
echo '<td>' .$row[4] . '</td>' ;
echo '<td>'."<a href='edit_movie.php?edit=" . $row[0] . "'>Edit</a>".'</td>';
echo '<td><form action="index.php" method="POST">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name="id" value="'. $row[0] .'" />
<input type="submit" value="Delete" /></form>
</td></tr>' ;
}
echo '</table>';
include 'add_movie.php';
?>
You forget to close action attribute.
You have echo '<td><form action="index.php method="POST"> change it to
echo '<td><form action="index.php" method="POST">
Just to be clear: 'mysql_query' and accompanying commands is deprecated and should really not be used. The OP however stated that it was required for an assignment. The easiest way to replace them is to use 'mysqli_*' instead. For an example using parameter binding to avoid sql-injection:
http://www.php.net/manual/en/mysqli-stmt.bind-param.php
Shouldn't it be:
if (isset($_POST['delete']) && isset($_POST['id'])) {
$id = mysql_real_escape_string($_POST['id']);
...
See this link for some info on 'get_post':
PHP: Having a problem with get_post
The problem there was that the function 'get_post' was defined on the next page of the course literature, wich the asker hadn't noticed.
The variable $_POST['id'] contains the id-value sent from a form via an HTTP POST-request. You check if that value is set, and then you should assign it to '$id' like i wrote.
Your delete sql has wrong quotes
$query = "DELETE FROM movies WHERE id='.$id.' LIMIT 1";
change to either
$query = "DELETE FROM movies WHERE id=".$id." LIMIT 1";
or
$query = "DELETE FROM movies WHERE id=$id LIMIT 1";
Try changing the form action
'<td><form action="index.php" method="POST">
Also check your database connection is properly established
Perhaps this might help for get_post
PHP: Having a problem with get_post
I'm pretty new to php, and for that matter server scripting in general (so go easy on me)
But regardless of that I managed to create this, the first half of a comment system:
<html>
<body>
<form name="Comment" action="InsertComment.php" method="POST">
Name: <input type="text" name="name" /><br>
Comment: <br><textarea style="height: 100px; width: 600px;" name="comment"></textarea><br>
<input id="Special_ID" name="id" value="<?php $unixtime = time(); echo $unixtime; ?>">
<!--^Gathers a unique id^-->
<input type="submit" />
</form>
</body>
</html>
Once submitted -->
<?php
$con = mysql_connect("Blaa", "Blaa", "Blaa");
if(!$con) {
die('Could not connect ' . mysql_error());
}
sql_select_db("Comments", $con);
$sql = "INSERT INTO Posts (Name, Comment, ID)
VALUES('$_POST[name]', '$_POST[comment]', '$_POST[id]')";
?>
This is exactly what I wanted, a user puts in their name, a comment, and a unique post id (time stamp) is generated, then it is all sent to mysql.
But now I'm dumb found as to how I can post this to another page..
I assumed something like:
if(ID == [the id of that post]) {
//$_GET the mysql stuff
//Post inside a specially made div or something
}
Along the lines of that, but I have no clue how to put that into practise :/
Any ideas?
Oh and Please don't suggest an echo type post, I've done that and it's not at all what I want.
**Also this is just the basic code, I don't need suggestions on how to touch it up just yet, also errors in this is only due to my sleep deprivation, the code does work.
As #Marc B has said, you'll first want to fix your SQL injection holes using mysql_real_escape_string. Change your insert statement to
$sql = "INSERT INTO Posts (Name, Comment, ID)
VALUES('" . mysql_real_escape_string($_POST['name']) . "', '" . mysql_real_escape_string($_POST['comment']) . "', '" . mysql_real_escape_string($_POST['id']) . "')";
To display your comment, try this
$sql = "SELECT Name, Comment, ID
FROM Posts
WHERE ID = '" . mysql_real_escape_string($_GET['PostID']) . "'";
$query = mysql_query($sql);
echo "<div id=\"comments_container\">";
while ($row = mysql_fetch_assoc($query))
{
echo "<div class=\"comment\">";
echo "<div class=\"name\">" . $row['Name'] . "</div>";
echo "<div class=\"comment_body\">" . $row['Comment'] . "</div>";
echo "</div>"
}
echo "</div>";
Then CSS style your DIVs using IDs and classes.
Just an example using mysql_fetch_object
Please sanitize your $_GET data before inserting to MySQL, this is a huge injection security flaw.
$sql = "SELECT * FROM Posts WHERE id={$id}"
$result = mysql_query($sql);
$obj = mysql_fetch_object($result)
if(is_object($obj))
{
echo "Welcome " . $obj->Name;
}
A full length example is given here:
http://manzur-ashraf.com/code/auto_commenting_system/Automatic_Commenting_System_and_Email_notification_using_PHP_and_MYSQL.htm
In addition to using a MYSQL database to store the comments, you can also post email to the admin about new comments.
I am trying to dynamically create php check-boxes linked to an MSSQL-Database. The idea is to List every item in the table, with a check box. From there the user will be able to check the check-boxes and click submit to change the value in 1 field of the Database to "A". I have the database linked to the php and It outputs the check-checkboxes and table values, however I do not know from there how to dynamically check the check-boxes to see if they are checked, or to use it from there.
This is roughly the approach you want to take to dynamically create checkboxes. There are of course prettier ways to accomplish this (i.e. Smarty templates).
<html>
...
<form method="post" action="submit.php">
<?php
// connect to DB here
$result = mysql_query("SELECT l.id, l.name, u.checked FROM List l LEFT JOIN UserAnswers u ON l.id = u.list_id WHERE u.user_id = 5");
while ($row = mysql_fetch_assoc($result))
{
echo '<input type="checkbox" name="cb_' . $row['id'] . '" ' .
'id="cb_' . $row['id'] . '" ';
if($row['checked'])
echo 'checked';
echo " />\n"
echo '<label for="cb_' . $row['id'] . '">' . $row['name'] . "</label><br />\n";
}
?>
<input type="submit" value="Submit" />
</form>
...
</html>
submit.php is a bit trickier. When a checkbox is checked, it will set a post item. However if it's unchecked, you won't get ANYTHING back, so you need to check your database for all the items you'll be expecting.
<?php
// connect to DB here
$result = mysql_query("SELECT id, name, checked FROM things");
$answers = Array();
while ($row = mysql_fetch_assoc($result))
{
$checked = isset($_POST['cb_' + $row['id']]);
$answers[$row['id']] = $checked;
}
// update your database here using $answers
foreach ($answers as $id => $checked)
{
$query = "REPLACE INTO UserAnswers SET user_id=5, list_id=" . $id . ", checked=";
if($checked)
$query .= "1";
else
$query .= "0";
mysql_query($query);
}
This is all off the top of my head, there are better ways to do most of this. It's just a general direction. I make no guarantees about any of this. Oh and it looks quite vulnerable to SQL injection, watch out for that.