save checked checkbox php - php

I need your help please to get something working.
I've a kind of a link parser which put the links in an array and displays them with a checkbox at the beggining of every link.
I've separated all the work into multiple files :
Form.php which contains only the HTML form.
Confing.php contains the necessary lines to connect to database.
New.php contains the source
and checkbox.php to save checked links in database.
Now, what I want is to be able to save only checked links in the database, but instead it saves everything.
Here's the code (in New.php) to add a checkbox to every link of the array :
// $r is the array
for($i=0;$i<sizeof($r);$i++)
{
echo "<input type='checkbox' name='recup[]' value='".$r[$i]."'>".$r[$i]."<br>";
}
$_SESSION[sup] =
At the end of this file, an action to start checkbox.php :
<form action="checkbox.php" method="post">
<input type='submit' name='Submit' value='Submit'>
The file chekbox.php :
<?php
include("config.php");
if($_POST["Submit"]=="Submit")
{
for ($i=0; $i<sizeof($r);$i++)
{
$query="INSERT INTO ub0oi_newcraw_liens(id,url,description) VALUE(NULL,'$r[$i]','Lien')";
mysql_query($query) or die ('Error updating database');
echo "Record is inserted.";
}
}
?>
I Only want to save the checked value, please help me.

you did not catch checkbox post value:
try this code:
<?php
include("config.php");
if(isset($_POST["Submit"]))
{
$r=$_POST['recup']; // you forget to add this line
for ($i=0; $i<sizeof($r);$i++)
{
$query="INSERT INTO ub0oi_newcraw_liens(id,url,description) VALUE(NULL,'$r[$i]','Lien')";
mysql_query($query) or die ('Error updating database');
echo "Record is inserted.";
}
}
?>

Related

Populating HTML Dropdown List using PHP/MYSQL

I was practicing using HTML/PHP/MySQL, and was working on a small project.
I wanted to create a page that would allow the user to add records to a MySQL table. The user would enter the values via an HTML form. This data would then be posted to a php script to perform the actual INSERT INTO.
The database is for a shop, and has 2 tables, product and manufacturer. When adding a product, I must also add a code for the manufacturer. I want to populate a dropdown list, showing the names of manufacturers (taken from the manufacturers table).
I am attempting to embed this PHP code into an HTML file. Here is the code:
<form action="" method="post">
<fieldset>
<legend>Enter Product Details:</legend>
Product Name:<input type="text" name="productName"><br>
Product Price:<input type="text" name="Price"><br>
<?php
$host="localhost";
$user="root";
$pass="";
$db="computer_shop";
$conn=mysqli_connect($host,$user,$pass,$db) or die ("Couldn't connect");
$sql="SELECT * FROM manufacturer";
$result=mysqli_query($conn,$sql) or die ("Could not execute query!");
if(!$result){
echo"Error with results";
}
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$code=$row["Code"];
$name=$row["Name"];
echo"<select name='select'>";
echo"<option value=" .$code.">".$name."</option>" ;
<echo"</select>";
}
echo "<br>";
} else {
echo "0 results";
}
mysqli_close($conn);
?>
<input type="submit" value="Submit">
</fieldset>
</form>
When I attempt this, it doesn't go well. When I load the page, the initial part of the form (with input boxes for name and price are fine), but the drop down list is a mess, and I see the code: "0) { while($row = mysqli_fetch_assoc($result)) { $code=$row["Code"]; $name=$row["Name"]; echo" along with a drop down list showing only $name, and then the submit button. So the HTML file is displaying part of the actual PHP code.
My question is, how do I fix this so that the drop down list will display the values from the mysql database? I have been looking through various sites, trying different things, but I keep getting a similar problem. Should I flip things, and embed the HTML inside a PHP file instead?
In general this code is not a good practice. Make sure that this code is in a .php file and your web server supports php.
Other than that, I think that the following script will solve your problem.
if (mysqli_num_rows($result) > 0) {
//open the select tag before the loop
echo"<select name='select'>";
//populate the select
while($row = mysqli_fetch_assoc($result)) {
$code=$row["Code"];
$name=$row["Name"];
echo"<option value=" .$code.">".$name."</option>" ;
}
//close the select tag after the loop
echo"</select>";
echo "<br>";
} else {
echo "0 results";
}

properly save file upload contents to MySQL DB to retrieve as a link

I am trying to build an upload component that saves the file information to a MySQL DB table. My first issue is that each time a user uploads a file, two entries are added to the database.
My next issue is that I was to grab an uploaded file and display it as a link for the user to click on to view in a new tab. Right now, the upload saves the file's server directory path. When I go to click on the file, I get an error message saying the directory path could not be found.
My biggest issue is the link problem to view the uploads. Then, if someone also has a suggestion for the double entry problem, that would also be appreciated.
My Code:
HTML: File upload feature - Successfully uploads all variables twice...
<form id="sgFileUpload" action='sg_addupload.php' target='hiddenFrame' method="POST" enctype="multipart/form-data">
<fieldset id='uploadBtnField'>
<input type="hidden" name="MAX_FILE_SIZE" value="50000000"/>
<input type='hidden' name='sgRef' id='sgRef' value='<?php echo $sgref ?>'>
<input type='file' name='searchFile' id='searchFile' multiple>
<input type='submit' name='startUpload' id='startUpload' value='Upload'>
</fieldset>
</form> <!-- End Form Input -->
My PHP: File upload to DB
if(isset($_POST['sgRef'])) {
$sgref=$_POST['sgRef'];
}
$fileName = $_FILES['searchFile']['name'];
$fSize = $_FILES['searchFile']['size'];
$fType = $_FILES['searchFile']['type'];
$target = "../bms/uploads/";
$fileTarget = $target.$fileName;
$tempFileName = $_FILES["searchFile"]["tmp_name"];
//$docType = $_POST['docType'];
$result = move_uploaded_file($tempFileName,$fileTarget);
if ($result) {
//run DB Connection code...
//Writes the information to the database
$sql="INSERT sg_uploads(sgref,file,type,size,content,doctype) VALUES('$sgref','$fileName','$fType','$fSize','$fileTarget','Other')";
$conn->query($sql);
if($conn->query($sql)) {
echo 'Your file <html><b><i>'.$fileName.'</i></b></html> has been successfully uploaded!';
} else {
//Gives an error if its not
echo "Sorry, there was a problem uploading your file.";
}
//Free the result variables.
$sql->free();
$result->free();
//Close the Database connection.
$conn->close();
}//End If Statement.
PHP CODE: To display links from DB (PHP CODE FOR RETRIEVAL IS SUCCESSFUL)
<?php
while ($row = $result->fetch_array()) {
echo "<tbody>";
echo "<tr>";
echo "<td>" . "<a href=".$row['content']."' >".$row['file']."</a>". "</td>";
echo "<br/>";
echo "<br/>";
}//end while.
echo "</tr>";
echo "</tbody>";
$filename = $row[0];
echo "<p></p>";
?>
All help is appreciated! Thank you!
NOTE: the 'file' column in the database is a datatype of 'blob'.
"#Fred, yes it was a directory issue. Upon fixing this issue, I was able to successfully link the the page and view it. If you summarize your two suggestions as an answer, I will mark your response as the correct answer. Thank you!"
As I stated in comments:
The duplicate entries are caused by $conn->query($sql); if($conn->query($sql))
where there were two instances of query() being used.
You can just use the conditional statement and omit $conn->query($sql);.
For the path issue, this was also stated in comments that the folder's path wasn't properly indexed.
Footnotes:
You're presently open to an SQL injection. Best you use a prepared statement.
https://en.wikipedia.org/wiki/Prepared_statement

PHP can't update SQL

I'm using a php part in my site, where I have a textarea that get a text from a database. The user can edit this text and after he finish press the save button, and using UPDATE I will change the text in the database.
Here is my code:
<?php
$con=mysqli_connect("localhost","userdb","codedb","projectdb");
mysqli_set_charset($con, 'utf8');
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$myQueryfac="SELECT text FROM main WHERE id=1";
$result = mysqli_query($con,$myQueryfac);
while($row = mysqli_fetch_array($result)) {
$t1=$row['text'];
}
$form="<form action='adminindex.php' method='post'>
<textarea name='area1' maxlength='1500' cols='50' rows='10'>$t1</textarea>
<input type='submit' name='enter' value='Save'>
</form>";
if($_POST['enter']) {
$t1=$_POST['area1'];
mysqli_query($con,"UPDATE main SET text='$t1' WHERE id='1'");
}
echo $form;
mysqli_close($con);
?>
My problem is in the UPDATE query it seems like it ignores $t1 and nothing change in database. But if I put something random in there, "RANDOM TEXT", change it successful.
This is how you do it:
test.php
// DB Connect
$con=mysqli_connect("localhost","userdb","codedb","projectdb");
mysqli_set_charset($con, 'utf8');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Handle POST
if (count($_POST))
{
// Save In DB
mysqli_query($con, sprintf("UPDATE main SET `text`='%s' WHERE id=%d",
mysqli_real_escape_string($con, $_POST['area1']),
1)); // id
// Success
echo "<p>Data updated.</p>";
}
// Load Existing Data
$myQueryfac="SELECT `text` FROM main WHERE id=1";
$result = mysqli_query($con, $myQueryfac);
$row = mysqli_fetch_array($result);
// Display Form
echo "<form action='test.php' method='post'>
<textarea name='area1' maxlength='1500' cols='50' rows='10'>". $row['text'] ."</textarea>
<input type='submit' name='enter' value='Save'>
</form>";
// DB Close
mysqli_close($con);
?>
What I've changed
Moved the post hander up (above the select statement), so that if an update occurs, the form will show the latest updated data
Your update query was treating the id as string, I formatted it to be a digit (%d)
Removed the while loop, you don't need it as it is a single row being returned
added sql-injection prevention (using sprintf and mysqli_real_escape_string)
added backticks `` around the db field name text (wasn't sure if this is a reserved word, because it's one of the sql data types)
Try to do
mysqli_query($con,"UPDATE main SET text='$t1' WHERE id=1");
Instead
mysqli_query($con,"UPDATE main SET text='$t1' WHERE id='1'");
It could be the WHERE condition that bring your problems
You are checking the $_POST array for a value not existing. enter is your submit button and will not send a value.
Try this:
if($_POST['area1']) {
$t1=$_POST['area1'];
mysqli_query($con,"UPDATE main SET text='$t1' WHERE id='1'");
}

having trouble getting selected value from php dynamic selection option

I want to show options from my database for users to check, but having trouble getting user's choice.
So, I write two php files,
the first one doing things like: getting data from database, displaying in select option, then submit value by post to and the second php file.
And the second php file just display the recieved value.
Here's the first php file:
<html>
<body>
<form method="post" action="second.php">
<Select name=”select_value”>
<?
//connect to server
$con = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE) or die("Error " . mysqli_error($con));
$query = "SELECT * FROM MYTABLE" or die("Error in the consult.." . mysqli_error($con));
$result = $con->query($query);
//display result in select option
while ($row = mysqli_fetch_array($result)) {
echo "<Option value=".$row['ENTRY_ID']."> ".$row['ENTRY_NAME']."</Option><br>";
}
mysqli_close($con);
?>
</Select>
</form>
</body>
</html>
And the second php file:
<?
$option = isset($_POST['select_value']) ? $_POST['select_value'] : false;
if($option) {
echo $_POST['select_value'];
} else {
echo "not getting value of select option";
exit;
}
?>
If this works fine, I should see the selected value by the second php file, but I keep recieving my echo "not getting value of select option".
There must be something wrong between select option and my recieving file.
Can someone help?
try this double quotes
<Select name="select_value">
instead of <Select name=”select_value”>

loading data from a mysql database table and using it within <input type="checkbox"> as an option

so i have this table in mysql called colegue in database addressbook1. it has the following fields: colegue_id, firstname, lastname, telephone and email. what i want is to get the data within the firstname column and display it within a form that uses checkboxes.for example:
checkbox jerry
checkbox mary
checkbox cindy
and so on. then, the checked data is supposed to be sent to a script which echoes the data selected. here's the code that loads data onto the page:
<?php
//connect to mysql
mysql_connect("localhost", "root", "");
//select database
mysql_select_db("adressbook1");
//select data from table
$query=("SELECT * FROM colegue");
//perform query
$result=mysql_query($query);
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>testing</title>
</head>
<body>
<h3>testing a checkbox form</h3>
<?php
//start the form
echo "<form method=\"post\" action=\"process.php\">";
while($row=mysql_fetch_array($result))
{
//assign value from associative array to variable
$data=$row['firstName'];
/*echo data and assign the value in the input the current value of $data while loading onto array*/
echo "<input type=\"checkbox\" name=\"firstname[]\" value=\"<?php $data;?>\">".$data." <br>";
}
echo "<br>";
//send data to process.php when clicked
echo "<input type=\"submit\" name=\"sent\" value=\"add\">";
echo "</form>";
?>
</body>
</html>
now for the script that processes the data:
<?php
//get the data from the form in an array
$entry=$_POST['firstname'];
//check if the array is empty or not
if (empty($entry))
{
echo("execution failed");
}
//if not empty, continue
else
{
//get the array size
$N=count($entry);
//display the size of the array
echo "$N"."<br>";
//this loop should display all the data in the array
for($i=0; $i<$N; $i++)
{
echo "$entry[$i]"."<br>";
}
//end script by showing successful result
echo ("request successful!");
}
?>
the code runs fine when i check the names i want sent and submit them to the script. the script does show me the size of the array, (e.g. if i clicked on four names, it shows me the number four) but it doesn't show me anything else, it doesn't display the actual names that i clicked on the page. could anyone kindly help me solve this? i'm thinking that maybe i haven't properly assigned values in the array firstname[].
Please note that i have to use this method (checkboxes) to submit the data gotten from the database so that it is displayed in the script-page. i am very new to programming, so i kindly ask for help, thanks.
You need to concatenate $data with the string, just alter
value=\"<?php $data;?>\"
too
value=\"".$data."\"

Categories