I have been reading through, testing, and coming up short from understanding how to create a MySQL statement that matches a column against an array of values...
Here's what I have...
<form id="form" action="index.php" method="post">
<?
$query = "SELECT Interest FROM Interests";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result))
{
echo '<input type="checkbox" name="Interest[]" value="' . $row['Interest'] . '" /> ' . $row['Interest'] . '<br />';
}
?>
<input id="Search" name="Search" type="submit" value="Search" />
</form>
<?
if (isset($_POST['Search']))
{
$InterestMatches = implode(',', $_POST['Interest']);
$query = "SELECT MemberID FROM MemberInterests WHERE Interest IN ( $InterestMatches )";
$result = mysql_query($query) or die(mysql_error());
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
while ($row = mysql_fetch_assoc($result))
{
$ResultingMemberIDs[] += $row['MemberID'];
}
}
?>
And what I always get is the same error...
Unknown column 'WhateverInterest' in 'where clause'
Can someone please tell me what I am doing wrong, what I need to do to correct this?
I suggest echoing out your query, it'll help with debugging. Your query currently looks like:
SELECT MemberID FROM MemberInterests WHERE Interest IN (WhateverInterest,Testing)
As you can see, in the IN the values are unquoted, so they're interpreted as field names. You need to add quotes around each value in the IN.
You can fix it by looping, and adding quotes around each value:
foreach($_POST['Interest'] as &$intrest){
$intrest = "'$intrest'";
}
$InterestMatches = implode(',', $_POST['Interest']);
Or by imploding with "','", and then adding quotes before and after:
$InterestMatches = "'" . implode("','", $_POST['Interest']) . "'";
P.S. You should mysql_real_escape_string each value in $_POST['Interest'] to avoid SQL injections.
Try
$InterestMatches = '"' . implode('","', $_POST['Interest']) . '"';
Related
I am trying to insert values to a database with a foreach loop. It all works fine but the last element of the array gets inserted twice.
I understand that a reference of a $photo and the last array element remain even after the foreach loop. I am trying to destroy it by using unset($photo) but that does not seem to work, I still get double insert inside my database of the last element.
Can someone explain this to me?
// value of $photos
<?php
$stmt = $conn->prepare(
"SELECT p.*, pt.propertyType
FROM tbl_property p
JOIN tbl_propertyType pt USING (PropertyType_Id)
ORDER BY Price;"
);
$stmt->execute();
?>
<form id = "prop-form" action="../scripts/photo-property.php" method = "POST" enctype="multipart/form-data">
<select name="property">
<?php while($row = $stmt->fetch()){ ?>
<option value="<?php echo $row['Property_Id'];?>"><?php echo $row['propertyType'] . ', ' . 'Price: ' . $row['Price'] . ', ' . $row['BuildingNameStreetNo']
. ', ' . $row['Street'] . ', ' . $row['Town'] . ', ' . $row['Condition']
. ', ' . $row['RoomNo'] . ' Rooms'; ?></option>
<?php } ?>
</select>
<?php $sql = $conn->prepare("SELECT * FROM tbl_Photo");
$sql->execute();
while($row = $sql->fetch()){
echo '<img class="propimg" src=../photos/'. $row['Photo'] . '><br/>';
echo '<input type="checkbox" name="photos[]" value="'. $row['Photo_Id'] . '">';
}
?>
</form>
-------------
// DIFFERENT FILE
// assign the array values from the form
$photos = $_POST['photos'];
// for each photo, bind the param and execute the query
$sql = $conn->prepare("INSERT INTO tbl_propertyphoto (Property_Id, Photo_Id) VALUES (:prop, :photo)");
foreach($photos as $photo) {
$sql->bindParam(':prop', $_POST['property']);
$sql->bindValue(':photo', $photo);
$sql->execute();
}
unset($photo);
Check if your tbl_Photo table hasn't multiple of the same rows.
Try to make the columns Property_Id and Photo_Id UNIQUE together.
In that way you cannot have the same combination twice.
ALTER TABLE tbl_propertyphoto ADD CONSTRAINT UQ_Property_Photo UNIQUE(Property_Id, Photo_Id)
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
There is nothing wrong with my code, but I just cant help but wonder, should I wrap the $key with mysql_real_escape_string? This is just part of my Database function which is mainly used to pull data out of the database with table name and $where as arguments to the function. $where is to be an associative array with keys being column name, and values being the data.
This is what processes the $where array. Before this I have $sql = 'select * from ' . $table;
if(!empty($where)){
$where_count = count($where);
$sql .= ' WHERE ';
foreach($where as $key => $value){
$split_key = explode(' ', $key);
if(count($split_key) > 1){
$sql .= $key[0] . ' ' . $key[1] . ' "' . mysql_real_escape_string($value) . '" ';
} else {
$sql .= $key . ' = "' . mysql_real_escape_string($value) . '" ';
}
}
}
Filter ANY INPUT from the user that is going to be placed in your query. No doubt!
So if the keys are supplied by the user, YES and if they are generated in a safe manner, NO.
Take a look at SQL Injection to understand why filtering must be done.
I am not sure what is being asked here, but I can see one error:
$sql .= $key[0] . ' ' . $key[1] . ' "' . mysql_real_escape_string($value) . '" ';
should be
$sql .= $split_key[0] . ' ' . $split_key[1] . ' "' . mysql_real_escape_string($value) . '" ';
If you really want to quote field names, use backticks.
See http://dev.mysql.com/doc/refman/5.6/en/identifiers.html
The following statement creates a table named a`b that contains a
column named c"d:
CREATE TABLE `a``b` (`c"d` INT);
I created a database with 3 tables being spusername, splocation, sprecord. spusername has id, splocation_id, lastname, firstname. I want to be able to have a drop down menu that has pulled id, lastname, firstname from the database, and within the pulldown it only shows a list of all the names being lastname,firstname. then once I select a person I have another drop down that has types of training in it. then when I hit submit it will generate a record in another table with the persons id and training record. so when I do a search it will pull up the user and the training records for that person.... I have already created a submit page in a .php that sends lastname, firstname, splocation_id for new users and I think I can create a search that does what I want it to, but I have never made a data entry doing a pulldown that has values generated from the database.
EDIT Code: With help from Vegard's coding I got this, and now it works great after a few trial and errors. Thank You!
Code:
<?php
if (isset($_REQUEST['Submit'])) {
$sql = "INSERT INTO $db_table(spusername_id,sptraining_id) values ('".mysql_real_escape_string(stripslashes($_REQUEST['spusername_id']))."','".mysql_real_escape_string(stripslashes($_REQUEST['sptraining_id']))."')";
if($result = mysql_query($sql ,$db)) {
echo '<h1>Thank you</h1>Your information has been entered into the database<br><br>';
} else {
echo "ERROR: ".mysql_error();
}
} else {
?>
<h1>Add Training Information To Database</h1><hr>
<br><br>
<form method="post" action="">
<select name="spusername_id">
<option value="default">Select Employee</option>
<?php
include("connectspusers.php"); /*file where you have stored your DB conn. settings*/
$result = mysql_query('SELECT id, lastname, firstname FROM spusername ORDER BY lastname ASC') or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['id'] . ' ' . $row['lastname'] . ' ' . $row['firstname'] . '">' . $row['lastname'] . ', ' . $row['firstname'] . '</option>';
}
?>
</select>
<select name="sptraining_id">
<option value="default">Select Training</option>
<?php
include("connectsptraining.php"); /*file where you have stored your DB conn. settings*/
$result = mysql_query('SELECT id, trainingtype, level FROM sptraining ORDER BY level ASC') or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['id'] . ' ' . $row['trainingtype'] . ' ' . $row['level'] . '">' . $row['trainingtype'] . ' - ' . $row['level'] . '</option>';
}
?>
</select>
<br><br>
<input type="submit" name="Submit" value="Submit">
</form>
<?php
}
?>
Something like this?
<select name="pulldown1">
<option value="default">Choose an option</option>
<?php
include("connect.php"); /*file where you have stored your DB conn. settings*/
$result = mysql_query('SELECT id, lastname, firstname FROM spusername ORDER BY firstname ASC') or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . htmlentities($row['id'], ENT_QUOTES) . ' ' . htmlentities($row['lastname'], ENT_QUOTES) . ' ' . htmlentities($row['firstname'], ENT_QUOTES) . '">' . htmlentities($row['lastname'], ENT_QUOTES) . ', ' . htmlentities($row['firstname'], ENT_QUOTES) . '</option>';
}
?>
</select>
<select name="pulldown2">
<option value="default">Choose and option</option>
<?php
$result = mysql_query('SELECT traingtype FROM trainingtable ORDER BY trainingname ASC') or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['trainingtype'] . '">' . $row['trainingtype'] . '" "' . $row['lastname'] . '</option>';
}
?>
</select>
This will result in two dropdown menus where the first dropdown lists the users last- and firstname separated by a comma+space and the second will list the different types of training. The ID filed is only sendt via the variable, but not displayed to the user.
When pulling the values from the variable in pulldown1, just use explode:
$userdetails = $_POST['pulldown1'];
$values = explode(" " $userdetails);
$ID = $values[0];
$lastname = $values[1];
$firstname = $values[2];
Haven't tested the code so it might need tweaking, and ofcourse you need to change the variable names corresponding to your actual db rownames.
Edit: In your code, you have to use $row and not $row2.
Secondly, instead of this:
<option value='{$id}'>{$lastname},{$firstname}</option>
use this:
<option value="' . $row['id'] . '">' . $row['lastname'] . ', ' . $row['firstname'] . '</option>
<select name="id" size="1">
<?php
$result=mysql_query("select * from spusername;");
while($user=mysql_fetch_array($result)) {
echo "<option value=\"".$user['id']."\">".$user['lastname'].", ".$user['firstname']."</option>";
?>
</select>
Go on with always using "id" as a reference to the user and try using post instead of get to send the request(keeps the URL in your user's browser clean).
You build a select in a loop with the data from your database.
example with mysql (did not test):
$query = "select id, lastname, firstname from spusername";
$result = mysql_query($query);
echo "<select>";
while($row = mysql_fetch_array($result)){
echo "<option value='".$row['id']."'>".$row['lastname']. " ". $row['firstname']."</option>";
}
echo "</select>";
EDIT: (response to your edit)
In your code you use $row2 instead of $row
Just an addendum to Vegard's solution:
Single quotes can be a bit tricky with surnames. It really depends on how you're storing the data in your database though.
If you have a surname O'Leary or O'Reilly you might get truncated results as you're building your select loop on the names. Give it a try.
You can fix this issue by using
htmlentities($row['lastname'], ENT_QUOTES) in your select loop