I'm trying to check if a color is already entered into the database if it is the color should not be entered and stored into the database and the following error code <p>This color has already been entered!</p> should be displayed. But for some reason I cant get this to work, can someone please help me?
The color names are entered into $_POST['color'] which is an array entered by the user.
Here is the html code that collects the colors.
<input type="text" name="color[]" />
<input type="text" name="color[]" />
<input type="text" name="color[]" />
<input type="text" name="color[]" />
<input type="text" name="color[]" />
<input type="text" name="color[]" />
<input type="text" name="color[]" />
<input type="text" name="color[]" />
<input type="text" name="color[]" />
Here is the PHP & MySQL code.
for($i=0; $i < count($_POST['color']); $i++) {
$color = "'" . $_POST['color'][$i] . "'";
}
$mysqli = mysqli_connect("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"SELECT *
FROM colors
WHERE color = '$color'
AND user = '$user_id' ");
if(mysqli_num_rows($dbc) == TRUE) {
echo '<p>This color has already been entered!</p>';
} else if(mysqli_num_rows($dbc) == 0) {
// enter the color into the database
}
To avoid unnecessary querys you should fetch all colors first and check against them:
$colors = array();
$mysqli = mysqli_connect("localhost", "root", "", "sitename");
if($result = mysqli_query($mysqli,"SELECT color FROM colors WHERE user = '$user_id' ") {
while($row = mysqli_fetch_array($result)) {
$colors[] = $row['color'];
}
mysqli_free_result($result);
}
foreach($_POST['color'] as $color) {
if(in_array($color, $colors) {
echo '<p>Color ' . $color . ' has already been entered!</p>';
}
else {
// enter the color into the database
}
}
Make sure to sanitize the user input!
You have more than one colors so you should use something like following.
$mysqli = mysqli_connect("localhost", "root", "", "sitename");
for($i=0; $i < count($_POST['color']); $i++) {
$color = "'" . $_POST['color'][$i] . "'";
$dbc = mysqli_query($mysqli,"SELECT *
FROM colors
WHERE color = '$color'
AND user = '$user_id' ");
if(mysqli_num_rows($dbc) == TRUE) {
echo '<p>'.$color.' color has already been entered!</p>';
} else if(mysqli_num_rows($dbc) == 0) {
// enter the color into the database
}
}
I'm guessing the issue you're runnig into is that the database connection is allready open when you try to enter the new values into the database.
The solution is to first fetch everything from the database store it in an array, then run your checks and add accordingly.
You should use the IN operator. For example,
$color = null;
for($i=0; $i < count($_POST['color']); $i++) {
if ($color == null)
$sep = '';
else
$sep = ',';
$color = $sep . "'" . $_POST['color'][$i] . "'";
}
$mysqli = mysqli_connect("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"SELECT *
FROM colors
WHERE color IN ($color)
AND user = '$user_id' ");
It isn't an answer actually, but very important thing to learn:
I mean the simple thing: at first you have to deal with SQL only, no PHP or HTML. Create an SQL query to check for the colors, run it, test it, and once you statisfied - go for PHP. try to create the same query from a variable, and compare with example one. Once finished, you can go for HTML at last.
So, development process must be split into 3 stages:
SQL stage. Create a query. If you don't know what query you want, Ask here on SO somethink like "I have 3 color names and a table. how to check if any of these colors exists in the table already". Once done - check it out to ensure query runs ok and return desired results.
PHP stage. Once you have a query, echo it from your PHP script. And write a code below, code which produce this query from some variables. Print it out to compare, until you get both queries identical.
HTML stage. Make an HTML form which will send color names into PHP script which will create SQL query from them and finally run it.
Remember: to know which query you want to run is very-very important! Without this knowledge you cannot go any further
Every answer here lack to mention SQL query itself.
Related
I have created a form that requires the user to input information on all fields and then submit the form. My goal is to get the user input and insert it into new records on the database. My current challenges are that since I used a for loop in PHP to create the table/form:
I can not access the input from $_POST
Not sure how to go about differentiating all of the rows and their inputs from each other (since I used a loop to create them). I was thinking an array...
Please see a screenshot of the form I am working with.
Below is what I have for my submit button.
if (isset($_POST['submit'])) {
$date = date('m\/d\/Y');
$ordnum = $_POST['cpOrderNumber'];
$ponum = $_POST['cpPoNumber'] . $_POST['cpPoNumberF'];
$palnum = $_POST['palnum'];
$casecount = $_POST['casecount'];
$cpsflot = $_POST['cpsflot'];
$sscc = $_POST['sscc'];
if(!empty($_POST['cpOrderNumber']) || !empty($_POST['cpPoNumber'])) {
require_once('mydatabase.php');
$query = "INSERT INTO ASN (date, ordnum, ponum, palnum, casecount, cpsflot, sscc )
VALUES ('$date', '$ordnum', '$ponum', '$palnum', '$casecount', '$cpsflot', '$sscc')";
$insert = sqlsrv_query($dbc, $query);
if( $insert === false ) {
die('Could not connect to database');
}
}
else {
die('Please enter the appropriate information');
}
sqlsrv_close($dbc);
}
And here is where I am having difficulty. I can get $date, $ordnum, and $ponum to insert into the database however $palnum will not. As you can see from what I've commented out I have tried to use an array.
<?php
for ($x = 1; $x < 25; $x++) {
echo
'<tr id="' .$x. '">
<td style="font-size: 160%" name="palnum" id="pallet">' .$x. '</td>
<td id="caseCount"><input type="number" name="casecount" id="inputText_Small" maxlength="2"/></td>
<td id="hilltopLot"><input type="text" name="cpsflot" id="inputText_Order" value="" maxlength="10"/></td>
<td id="sscc"><input type="number" name="sscc" id="inputText_Medd" value="" maxlength="4"/></td>
</tr>';
$palnum[$x] = $x;
//$palnum[$x] = 'palnum'.$x;
//$palnum = $palnumx.$x;
//$palnum1 = $palnum[1];
}
//echo count($palnumx);
//echo $palnum[1];
?>
i think you are looking for this. not 100% though. Basically, you can name an input wityh brackets to make it behave like an array in the post.
<input name="recurringName[]" value="moo" />
<input name="recurringName[]" value="moo2" />
if you do that, in the post you can access data this way
$_POST['recurringName'][0] == 'moo'
$_POST['recurringName'][1] == 'moo2'
i hope this helps! let me know if i did not understand you clearly
In insert form I am using check boxes to insert values in database. Now, I want to get checked values in edit form so I can check new values or uncheck checked values.
First I get values from database (I am using pdo, I will not post connection code to db- it works):
get oprmea from database
$sql_oprema = "SELECT Oprema FROM dbo_emarketing_stavke_oprema WHERE Partner='$id'";
$n = $conn->query($sql_oprema);
while ($r = $n -> fetch()) {
$oprema_sql = $r['Oprema'];
}
I get values when I dump variables, output is not NULL.
I am using function to store values in database. Now I want to use same function for editing if posssible.
function emarketing_oprema(){
$link = new mysqli("localhost", "root", "le30mu09", "websoft");
$link->set_charset("utf8");
$sql=mysqli_query($link, "SELECT * FROM `dbo_emarketing_oprema` order by OpremaId asc ");
while($record = mysqli_fetch_array($sql)) {
echo '<input type="checkbox" name="oprema[]" value="'.$record['OpremaId']. '">' . $record['OpremaNaziv'] . ' <br/><br/> </input>';
}
}
I was wondering is it possible to use this function to get checked values checked.
use checked attribute
<input type="checkbox" checked>
or like this
<input type="checkbox" checked="checked">
You php will look like this:
while($record = mysqli_fetch_array($sql)) {
data='<input type="checkbox" name="oprema[]" value="'.$record["OpremaId"];
if(isset($record['checked'])) {//field in the database
data+=' checked="checked';
}
data+='">'. $record["OpremaNaziv"].'</br>';
}
This is my first php project. I have created a website where users can upload their picture and then view the pictures of other users, one person at a time (similar to the old hotornot.com). The code below works as follows:
I create an array (called $allusers) containing all members except for the user who is currently logged in ($user).
I create an array (called $usersiviewed) of all members who $user has previously either liked (stored in the likeprofile table) or disliked (stored in the dislikeprofile table). The first column of likeprofile and dislikeprofile has the name of users who did the liking/disliking, second column contains the name of the member they liked/disliked.
I use the array_diff to strip out $usersiviewed from $allusers. This is the list of users who $user can view (ie, people they have not already liked or disliked in the past).
Now the problem is when I click the like button, it updates the likeprofile table with the name of the NEXT person in the array (i.e., not the person who's picture I am currently looking at but person who's picture appears next). Additionally, if I refresh the current page, the person who's profile appears on the current page automatically gets 'liked' by me. I would really appreciate any advice on this.
<?php
// viewprofiles.php
include_once("header.php");
echo $user.' is currently logged in<br><br>';
echo <<<_END
<form method="post" action="viewprofiles.php"><pre>
<input type="submit" name ="choice" value="LIKE" />
<input type="submit" name ="choice" value="NEXT PROFILE" />
</pre></form>
_END;
$allusers = array();
//Create the $allusers array, comprised of all users except me
$result = queryMysql("SELECT * FROM members");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
if ($row[0] == $user) continue;
$allusers[$j] = $row[0];
}
//Create the $i_like_these_users array, comprised of all users i liked
$result = queryMysql("SELECT * FROM likeprofile WHERE user='$user'");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
$i_like_these_users[$j] = $row[1];
}
//Create the $i_dislike_these_users array, comprised of all users i disliked
$result = queryMysql("SELECT * FROM dislikeprofile WHERE user='$user'");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
$i_dislike_these_users[$j] = $row[1];
}
//Create the $usersiviewed array, comprised of all users i have either liked or disliked
if (is_array($i_like_these_users) && is_array($i_dislike_these_users))
{
$usersiviewed = array_merge($i_like_these_users,$i_dislike_these_users);
}
elseif(is_array($i_like_these_users))
{
$usersiviewed = $i_like_these_users;
}
else
{
$usersiviewed = $i_dislike_these_users;
}
// this removes from the array $allusers (i.e., profiles i can view) all $usersviewed (i.e., all the profiles i have already either liked/disliked)
if (is_array($usersiviewed))
{
$peopleicanview = array_diff($allusers, $usersiviewed);
$peopleicanview = array_values($peopleicanview); // this re-indexes the array
}
else {
$peopleicanview = $allusers;
$peopleicanview = array_values($peopleicanview); // this re-indexes the array
}
$current_user_profile = $peopleicanview[0];
echo 'check out '.$current_user_profile.'s picture <br />';
if (file_exists("$current_user_profile.jpg"))
{echo "<img src='$current_user_profile.jpg' align='left' />";}
// if i like or dislike this person, the likeprofile or dislikeprofile table is updated with my name and the name of the person who liked or disliked
if (isset($_POST['choice']) && $_POST['choice'] == 'LIKE')
{
$ilike = $current_user_profile;
$query = "INSERT INTO likeprofile VALUES" . "('$user', '$ilike')";
if (!queryMysql($query)) echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
if (isset($_POST['choice']) && $_POST['choice'] == 'NEXT PROFILE')
{
$idontlike = $current_user_profile;
$query = "INSERT INTO dislikeprofile VALUES" . "('$user', '$idontlike')";
if (!queryMysql($query)) echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
?>
Because when you refresh page it sends previus value of
Form again...and problem when u like a user it being liked next user.. There there is something in yor for loop while fetching row ...insted of for loop try once while loop ...i hope it will solve ur problem
You are calculating the $iLike variable with the currently loaded user and then updating the database with that user.
You should probably change your application logic a bit:
pass the user ID of the user you liked or did not like as a POST parameter in addition to the like/didn't like variable
move the form processing logic to the top of your page (or better yet separate out your form processing from HTML display)
Also, it's best not to use the mysql_* extensions in PHP. Use mysqli or PDO.
Try to make two different forms. One with "LIKE", another with "NEXT" to avoid liking from the same form
When you submit your form - your page refreshes, so in string $current_user_profile = $peopleicanview[0]; array $peopleicanview doesn't have user from previuos page (before submitting) you have to attach it, e.g. in hidden field
<form method="post" action="viewprofiles.php">
<input type="hidden" name="current_user" value="$current_user_profile" />
<input type="submit" name ="choice" value="like" />
</form>
<form method="post" action="viewprofiles.php">
<input type="submit" name ="go" value="next" />
</form>
and INSERT it later
"INSERT INTO likeprofile VALUES" . "('$user', '".$_POST['current_user']."')"
ps remove <pre> from your form
Lets start by simplifying and organizing the code.
<?php
// viewprofiles.php
include_once("header.php");
//if form is sent, process the vote.
//Do this first so that the user voted on wont be in results later(view same user again)
//use the user from hidden form field, see below
$userToVoteOn = isset($_POST['user-to-vote-on']) ? $_POST['user-to-vote-on'] : '';
// if i like or dislike this person, the likeprofile or dislikeprofile table is updated with my name and the name of the person who liked or disliked
if (isset($_POST['like']))
{
$query = "INSERT INTO likeprofile VALUES" . "('$user', '$userToVoteOn ')";
if (!queryMysql($query))
echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
if (isset($_POST['dislike']))
{
$query = "INSERT INTO dislikeprofile VALUES" . "('$user', '$userToVoteOn ')";
if (!queryMysql($query))
echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
//now we can create array of available users.
$currentProfileUser = array();
//Create the $currentProfileUser array,contains data for next user.
//join the 2 other tables here to save php processing later.
$result = queryMysql("SELECT `user` FROM `members`
WHERE `user` NOT IN(SELECT * FROM `likeprofile` WHERE user='$user')
AND `user` NOT IN(SELECT * FROM `dislikeprofile` WHERE user='$user')
and `user` <> '$user'
LIMIT 1");
//no need for a counter or loop, you only need the first result.
if(mysql_num_rows > 0)
{
$row = mysql_fetch_assoc($result);
$current_user_profile = $row['user'];
}
else
$current_user_profile = false;
echo $user.' is currently logged in<br><br>';
//make sure you have a user
if($current_user_profile !== false): ?>
<form method="post" action="viewprofiles.php">
<input type="hidden" name="user-to-vote-on" value="<?=$current_user_profile?>" />
<input type="submit" name ="like" value="LIKE" />
</form>
<form method="post" action="viewprofiles.php">
<input type="hidden" name="user-to-vote-on" value="<?=$current_user_profile?>" />
<input type="submit" name ="dislike" value="NEXT PROFILE" />
</form>
check out <?=$current_user_profile?>'s picture <br />
<?php if (file_exists("$current_user_profile.jpg")): ?>
<img src='<?=$current_user_profile.jpg?>' align='left' />
<?php endif; //end check if image exists ?>
<?php else: //no users found ?>
Sorry, there are no new users to view
<?php endif; //end check if users exists. ?>
You'll notice I changed the code a lot. The order you were checking the vote was the main reason for the issue. But over complicating the code makes it very difficult to see what's happening and why. Make an effort to organize your code in the order you expect them to run rather a vote is cast or not, I also made an effort to separate the markup from the logic. This makes for less of a mess of code to dig through when looking for the bug.
I also used sub queries in the original query to avoid a bunch of unnecessary php code. You could easily have used JOIN with the same outcome, but I think this is a clearer representation of what's happening. Also please use mysqli instead of the deprecaded mysql in the future, and be aware of SQL injection attacks and makes use of real_escape_string at the very least.
Hope it works out for you. Also I didn't test this code. Might be a few errors.
I have a website, where a user can enter a time series (date; series) into a text area. The data is sent to the server using the POST method.
I have a few tables with different time series already stored in the MySQL database.
The user specified time series and those stored in the database should be combined for statistical calculations.
I store the user input into an array using explode and want to select the time series from the database using the date as the selector (WHERE date = $datefromuserinput).
I have two problems here:
The date format for the array does not match the one in MySQL (ISO, o-m-d) after several transformations (e.g. strtotime).
Also, the time series data type in MySQL is in DECIMAL (15,4) format, but the one in PHP is string (transformed to float).
Before trying to find solutions, I would like to know if my concept is right and best. Putting the user input into a MySQL table would make calculations faster (as I understand). However, several users can use the form simultaneously that would result in overwriting the entries in the new table in MySQL, right? Should I load the complete MySQL table into a PHP array (session necessary)?
I have read many solutions but could not find these answer. Any hint would be highly appreciated.
<?php
date_default_timezone_set('UTC');
//session_start();
//$datum = [];
if ($_POST['usersubmit']) {
if ($_POST['userinput1'] !=""){
if ($_POST['separator'] != ""){
if ($_POST['separator'] == comma){
$separatorsign = ",";
}
elseif ($_POST['separator'] == semicolon){
$separatorsign = ";";
}
else {
$separatorsign = "\t";
}
}
$userinput1 = $_POST['userinput1'];
$zeilen= explode("\n", $userinput1);
$daten = array();
foreach($zeilen as $zeile) {
list($datum, $zeitreihe) = explode($separatorsign, $zeile,2);
$datumkonv = strtotime($datum);
$daten[]['datum'] = date('o-m-d',$datumkonv);
$daten[]['zeitreihe'] = $zeitreihe;
}
$con = mysql_connect('localhost','username','pw');
if (!$con)
{
die('Could not connect: ' . mysql_error($con));
}
mysql_select_db("dbname");
$sql = "SELECT series FROM mytimeseries1 WHERE date = $daten[0]['datum']"; //[0] just for trying working with the first row
$result = mysql_query($sql);
$row = mysql_fetch_object($result);
echo "$row->series";//["series"].'<br>';
$row = floatval($row);
$ergebnis = $row + 22;
echo $ergebnis; // $row is 100.5000 but $ergebnis returns 100.5023 ??
mysql_free_result($result);
mysql_close($con);
echo "<pre>";
//print_r ($result);
print_r ($row);
var_dump($row);
var_dump($ergebnis);
}
}
?>
<table width="800">
<tr>
<td width="400">
<form action="test.php" method="post">
<p><textarea style="overflow-y:scroll;resize:none;" name="userinput1" id="userinput1" cols="28" rows="12"></textarea></p>
<p>Separator<br>
<input type="radio" name="separator" value="comma">Comma</p>
<p><input type="radio" name="separator" value="tab">Tab</p>
<p><input type="radio" name="separator" value="semicolon">Semicolon</p>
</td>
<td width="400">
<p>Date Format<br>
<input type="radio" name="dateformat" value="yyyy-mm-dd">YYYY-MM-DD</p>
<p><input type="radio" name="dateformat" value="yyyy-dd-mm">YYYY-DD-MM</p>
<p><input type="radio" name="dateformat" value="dd-mm-yyyy">DD-MM-YYYY</p>
<p><input type="radio" name="dateformat" value="mm-dd-yyyy">MM-DD-YYYY</p>
<p><input type="radio" name="dateformat" value="ddmmyyyy">DD.MM.YYYY</p>
<p><input type="submit" name="usersubmit" value="GO"></p>
</form>
</td>
</tr>
</table>
<?php
EDIT: After trying for hours I think that it makes more sense to upload the user input array into a temporary table in MySQL (date format is accepted etc). I had to change the foreach()-part in the code above to:
for($y = 0;$y < count($zeilen);$y++){
list($datum, $zeitreihe) = explode($separatorsign, $zeilen[$y], 2);
$daten[$y]['datum'] = $datum;
$daten[$y]['zeitreihe'] = $zeitreihe;
}
This is a continuation of the discussion at
PHP Multiple Dropdown Box Form Submit To MySQL
which ended with the words: "Once you have the variables, it is trivial to create new rows." No doubt that's generally true, but apparently not for this learner... :-D
Given the following form:
<form action="form.php" method="POST">
<select name="colors[]" multiple="yes" size="2">
<option>Red</option>
<option>Blue</option>
</select>
<input type="submit" value="Go!">
</form>
how do I create new rows? The following script
foreach($_POST['colors[]'] as $color)
{
$id = mysqli_real_escape_string($link, $color);
$sql = "INSERT INTO colors SET id = '$id'";
}
raises the error
Warning: Invalid argument supplied for foreach() in form.php on line ...
whereas the following
$colors = $_POST['colors[]'];
for ($i = 0; $i < count($colors); $i++)
{
$color = $colors[$i];
$sql = "INSERT INTO colors SET id = '$color'";
}
raises no errors but does no row creation.
What triviality am I missing here?
Use:
foreach($_POST['colors'] as $color)
No need to specify [] here, php knows that it is an array.
Inside of your foreach loop I did not see that you are executing the query. You need to execute mysql_query with your INSERT statement.
foreach($_POST['colors'] as $color) {
$id = mysqli_real_escape_string($link, $color);
$sql = "INSERT INTO colors SET id = '$id'";
if (!mysql_query($sql)) { // if the query encountered a problem.
die('Invalid query: ' . mysql_error());
}
}