I have the following code, whenever I try to insert the data, the $content is not being inserted, where might the problem be? I am using the function test input for security related issues.
<?php
// define variables and set to empty values
$title = $content = $path = $file_type ="";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$title = test_input($_POST["title"]);
$content = test_input($_POST["content"]);
$path = test_input($_POST["path"]);
$file_type = test_input($_POST["file_type"]);
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$con=mysqli_connect("localhost","---","---","---");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO articles (ArtID,Title,Content,Image_VideoLink_Path,file_type)
VALUES
('','$title','$content','$path',' $file_type')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "<h2 >Article Published</h2>";
echo"<a href='../mag/index.php'> View it Now </a>";
mysqli_close($con);
?>
here is the code for the form:
<form method="POST" action="artPro.php">
<fieldset>
<legend>Create New Article</legend>
<br/>
Article Title:
<input type="text" placeholder="enter title here" class="span3" name="title" required>
Image/Video Path :
<input type="text" placeholder="enter image name e.g k.jpg or k.mp4 for video" name="path" class="span3" required/>
File Type :
<input type="text" name="file_type" class="span3" required placeholder="e.g: image or video"/>
<br/>
<label>Article Content:</label>
<textarea name="content" rows="20" class="jqte-test span12" required id="txtmsg"></textarea>
<br><button type="submit" class="btn btn-primary btn-large pull-right">Publish</button>
</fieldset>
</form>
Try this query:
$sql="INSERT INTO articles
(Title,Content,Image_VideoLink_Path,file_type) VALUES
('$title','$content','$path',' $file_type')";
$content was not being inserted because you are giving Article ID. And I am sure that Article ID will your primary key and this will auto incremented. So, you did not need to mention Article id in sql query (statement).
Related
I have The following form inputs I am trying to send these input data to "placebet.php" then retrieve the data and add a confirm or cancel button, then It can add to the database
<form action="placebet.php" method="post">
<div id="box" class="boxlit">
<div class="box" data-id="0">Myanmar - Vietnam<br>Home [1]<div class="crtTotal">4.30</div>
<input type="hidden" name="kickoff[]" value="7/17/2022 10:00">
<input type="hidden" name="match[]" value="Myanmar - Vietnam">
<input type="hidden" name="result[]" value="Home [1]" readonly="">
<input type="hidden" name="value[]" value="4.30"></div>
<div class="box" data-id="4">Thailand - Philippines<br>Draw [2]<div class="crtTotal">3.20</div>
<input type="hidden" name="kickoff[]" value="7/17/2022 13:30">
<input type="hidden" name="match[]" value="Thailand - Philippines">
<input type="hidden" name="result[]" value="Draw [2]" readonly="">
<input type="hidden" name="value[]" value="3.20"></div>
<div class="box" data-id="11">Botswana - Cameroon<br>Away [3]<div class="crtTotal">1.35</div>
<input type="hidden" name="kickoff[]" value="7/17/2022 22:00">
<input type="hidden" name="match[]" value="Botswana - Cameroon">
<input type="hidden" name="result[]" value="Away [3]" readonly="">
<input type="hidden" name="value[]" value="1.35"></div></div><br>
<input type="hidden" name="account[]" value="0818054386" readonly="">
<input type="hidden" name="balance[]" value="20" readonly="">
<input type="hidden" id="todds" name="todds[]" value="18.58" readonly="">
<input type="hidden" id="inp" name="payout[]" value="92.90" readonly="">
<div>Total Odds: <b id="ct1">18.58</b></div><br>
<div>(N$)Stake: <input id="stake" type="number" name="stake[]" value="5"> NAD</div><br>
<div>Payout: N$ <b id="payout">92.90</b></div>
<input class="bet1" type="submit" name="submit" value="Bet">
</form>
Php code in "placebet.php"
I'm not sure if the code below is correct but I need it to show the input data from the form and give me a option to confirm the data(button) and then it can finally add to the database
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "forms");
$dba = mysqli_connect("localhost","root","","login");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$error = false; //set the error status value
$error_msg = "";
$back = mysqli_real_escape_string($link, $_REQUEST['kickoff'][0]);
$total = count($back); // get the length of the match
for($i=0;$i<$total;$i++){
// Escape user inputs for security
$kickoff = mysqli_real_escape_string($link, $_REQUEST['kickoff'][$i]);
$match = mysqli_real_escape_string($link, $_REQUEST['match'][$i]);
$selection = mysqli_real_escape_string($link, $_REQUEST['result'][$i]);
$odd = mysqli_real_escape_string($link, $_REQUEST['value'][$i]);
$account = mysqli_real_escape_string($link, $_REQUEST['account'][0]);
$stake = mysqli_real_escape_string($link, $_REQUEST['stake'][0]);
$payout = mysqli_real_escape_string($link, $_REQUEST['payout'][0]);
$todds = mysqli_real_escape_string($link, $_REQUEST['todds'][0]);
$accabal = mysqli_real_escape_string($link, $_REQUEST['balance'][0]);
//run sql query for every iteration
$charge = mysqli_query($dba, "UPDATE users SET balance = $accabal- $stake WHERE username='".$_SESSION['username']."'") ;
$_SESSION["balance"] = $accabal- $stake ;
$date = date ('Ymd');
$create = mysqli_query($link,"CREATE TABLE R$date LIKE receipts") ;
$insert = mysqli_query($link,"INSERT INTO `R$date`(`Match`, `Selection`, `Odd`,`Account`,`Stake Amount`,`Payout`,`Total Odds`) VALUES ('$match','$selection','$odd','$account','$stake','$payout','$todds')");
if(!$insert)
{
$error = true;
$error_msg = $error_msg.mysqli_error($link);
}
//check your error status variable and show your output msg accordingly.
if($error){
echo "Error :".$error_msg;
}else{
header("location: index.php");
exit;
}
}
mysqli_close($db);
?>
What you want to do isn't redirect to index.php, cause with this you start a new request and cant point on the request data of placebet.php anymore.
You want either to send your form via javascript ajax request and then react to the response of placebet.php (https://www.w3schools.com/js/js_ajax_intro.asp) or generating your own new output at placebet.php which then can be a confirm page or something similar.
e.g.
if($error){
echo "Error :".$error_msg;
}else{
echo "Data has been stored!";
}
You also could put your html at the end of the php file after closing the php part with ?> like mentioned here https://www.thoughtco.com/php-with-html-2693952#:~:text=As%20you%20can%20see%2C%20you,re%20inside%20the%20PHP%20tags).
I am having a trouble to saving data into the database. My connection details and sql insert query everything is correct and image is also uploading to folder but I do not know why data along with image is not saving into an database when i hit upload button.Can anyone help me please?
My php code
<?php
include('server.php');
$userID = 1;
if(isset($_SESSION['username']))
{
$userName = $_SESSION['username'];
$queryID = "SELECT id from users WHERE username = '$userName'";
$resultID = $db->query($queryID);
$row=$resultID->fetch_assoc();
$userID = $row['id'];
}
if(isset($_POST['submit']))
{
$image = $_FILES['image']['name'];
$target = "images/".basename($image);
$eventName = $_POST['eventName'];
$eventDetail = $_POST['eventDetail'];
$eventDate = $_POST['eventDate'];
$eventTime = $_POST['eventTime'];
$queryImage = "INSERT INTO event_detail(eventName,eventDetails,eventDate,eventTime,imagePath,userID) VALUES('$eventName','$eventDetail','$eventDate','$eventTime','$image','$userID')";
mysqli_query($db,$queryImage);
if(move_uploaded_file($_FILES['image']['tmp_name'],$target))
{
$msg = "Image uploaded successfully";
}
else
{
$msg = "There is problem";
}
}
?>
html
<form method="post" enctype="multipart/form-data">
<label for="eventName">Event Name:<label>
<input type="text" id="eventName" name="eventName" ><br><br>
<label for="eventDetail">Event Detail:<label>
<textarea id="eventDetail" name="eventDetail" ></textarea><br><br>
<label for="eventDate">Event Date:<label>
<input type="text" id="eventDate" name="eventDate" ><br><br>
<label for="eventTime">Event Time:<label>
<input type="text" id="eventTime" name="eventTime" ><br><br>
<input type="file" id="image" name="image"><br><br>
<button type="submit" id="submit" name="submit" >Submit</button>
</form>
Change this
$queryImage = "INSERT INTO event_detail(eventName,eventDetails,eventDate,eventTime,imagePath,userID) VALUES ('$eventName','$eventDetail','$eventDate','$eventTime','$image','$userID')";
to
$queryImage = "INSERT INTO event_detail(eventName,eventDetails,eventDate,eventTime,imagePath,userID) VALUES ($eventName,$eventDetail,$eventDate,$eventTime,$image,$userID)";
I have written the below HTML code:
<form action="index.php" method="POST">
<input type="text" name="title" required>
<input type="text" name="brief_text" required>
<textarea name="text" required></textarea>
<input type="submit" name="add" value="Add">
</form>
My PHP code:
<?php
require_once('db.php');
if(isset($_POST['add'])){
$title = $_POST['title'];
$brief_text = $_POST['brief_text'];
$text = $_POST['text'];
$blog_cat_id = $_POST['blog_cat_id'];
if($title AND $brief_text AND $text AND $blog_cat_id){
$insert_blog = "insert into blog values ('','$title','$brief_text','$text','$blog_cat_id',NOW())";
$run_insertion = mysqli_query($con, $insert_blog);
if($run_insertion){
echo "Blog has been added!";
}
else{
echo "Error adding blog!!!";
}
}
else{
echo "All fields are required!";
}
}
else{
echo "GOODBYE";
}
?>
Every time I refresh the page, it only shows the form and "GOODBYE" and does not even insert the data into database table.
Help me out please.
Is it still showing 'GOODBYE' now you've changed
$_POST['add_blog']
to
$_POST['add']
when you click submit?
You have few mistakes,
1) should be: $_POST['add'] instead of $_POST['add_blog']
2) don't have $_POST['blog_cat_id'] as not in form
EDIT
Copied your code and made some changes:
code:
if(isset($_POST['add'])){
print_r($_POST);
$title = $_POST['title'];
$brief_text = $_POST['brief_text'];
$text = $_POST['text'];
$blog_cat_id = $_POST['blog_cat_id'];
if($title AND $brief_text AND $text AND $blog_cat_id){
echo "inside condition";
$insert_blog = "insert into blog values ('','$title','$brief_text','$text','$blog_cat_id',NOW())";
$run_insertion = mysqli_query($con, $insert_blog);
if($run_insertion){
echo "Blog has been added!";
}
else{
echo "Error adding blog!!!";
}
}
else{
echo "All fields are required!";
}
}
else{
echo "GOODBYE";
}
HTML:
<form action="index.php" method="POST">
<input type="text" name="title" required>
<input type="text" name="brief_text" required>
<input type="text" name="blog_cat_id" required>
<textarea name="text" required></textarea>
<input type="submit" name="add" value="Add">
</form>
output
Array ( [title] => test [brief_text] => test [blog_cat_id] => 1 [text] => testing [add] => Add )
inside condition
Now, check your query if doesn't work.
Hope this will help you.
Your query is wrong, columns are not specified and you are open to sql injection you should learn to use parameterized query. but for this time you can use the following.
Try this:
htmlcode
<form action="index.php" method="POST">
<input type="text" name="title" required>
<input type="text" name="brief_text" required>
<input type="text" name="blog_cat_id" required>
<textarea name="text" required></textarea>
<input type="submit" name="add" value="Add">
</form>
index.php
<?php
require_once('db.php');
if(isset($_POST['add'])){
$title = $_POST['title'];
$brief_text = $_POST['brief_text'];
$text = $_POST['text'];
$blog_cat_id = $_POST['blog_cat_id'];
if($title AND $brief_text AND $text AND $blog_cat_id){
$insert_blog = "insert into blog('col1','col2','col3','col4','col5','col6') values ('','$title','$brief_text','$text','$blog_cat_id',NOW())";
$run_insertion = mysqli_query($con, $insert_blog);
if($run_insertion){
echo "Blog has been added!";
}
else{
echo "Error adding blog!!!";
}
}
else{
echo "All fields are required!";
}
}
?>
Note : col1, col2, col3, col4, col5 and col6 will be your column name.
i have a code for updating data to myql. It looks doesn't have a problem but it ain't changed
my update code :
//previous data//
....
if (isset($_POST['update'])) {
$nim = mysqli_real_escape_string($connection, ($_POST['nim']));
$name = mysqli_real_escape_string($connection, ($_POST['name']));
$class1 = mysqli_real_escape_string($connection, ($_POST['class2']));
$class2 = mysqli_real_escape_string($connection, ($_POST['class1']));
if (!preg_match("/^[1-9][0-9]*$/",$nim)) {
$error = true;
$nim_error = "NIM only contain numbers";
}
if (!preg_match("/[^a-zA-Z]/",$name)) {
$error = true;
$name_error = "NIM only contain numbers";
}
if (!preg_match("/^[1-9][0-9]*$/",$class1)) {
$error = true;
$class1_error = "Class only contain numbers";
}
if (!preg_match("/^[1-9][0-9]*$/",$class1)) {
$error = true;
$class2_error = "Class only contain numbers";
}
$result = "UPDATE users SET nim='$nim', name='$name', class1='$class1', class1='$class1' WHERE id='$id'";
mysqli_query($connection, $result);
}
?>
and this is my html code :
<div id="popup2" class="overlay">
<div class="popup">
<h2 class="range2">Edit</h2>
<a class="close" href="#">×</a>
<div class="content">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input class="input" type="text" name="nim" placeholder="NIM" required/>
<input class="input" type="text" name="name" placeholder="Name" required/>
<i>SK</i>
<input class="input1" type="text" name="class1" placeholder="00" required/>
<i>-</i>
<input class="input1" type="text" name="class2" placeholder="00" required/>
<input name="update" type="submit" class="button" id="submit" value="Submit">
</form>
</div>
</div>
</div>
is there any wrong code ? Thank you..
It is really hard to explain: Take a look.
If you want to update a single data you will need a identity(Primary
key). That mean which data you want to update.
Below Example: check index.php file
In file index.php change dbname to your database name in connection.
browse project_url/index.php?id=1 [here use any id from your database]
Then update your data.
index.php
//Show existed data againist id
if(isset($_GET['id'])){
$id = $_GET['id'];
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->execute(array('id'=>$id));
$data = $stmt->fetch();
if (empty($data)) {
echo "No data found in user table. Use proper ID.";
}
}
//Update query
$msg = array();
if (isset($_POST['id']) && $_POST['id']!='') { //operation is update, because id exist
if($_POST['nim']!=0 && is_numeric($_POST['nim'])){
$nim = $_POST['nim'];
}else{
$msg[]="Nim only can be number";
}
if($_POST['name']!=''){
$name = $_POST['name'];
}else{
$msg[]="came only can not be empty";
}
if(is_numeric($_POST['class1'])){
$class1 = $_POST['class1'];
}else{
$msg[]="Class1 only can be number";
}
if(is_numeric($_POST['class2'])){
$class2 = $_POST['class2'];
}else{
$msg[]="Class1 only can be number";
}
$id = $_POST['id'];
if(count($msg)==0){
$stmt = $pdo->prepare('UPDATE users SET nim=:nim, name=:name, class1=:class1, class2=:class2 WHERE id=:id');
$result = $stmt->execute(array(
'nim' => $nim,
'name' => $name,
'class1'=> $class1,
'class2'=> $class2,
'id' => $id,
));
if($result){
echo "successfully updated.";
}else{
echo "update failed";
}
}
}else{
//You can run here insert operation because id not exist.
echo "Id not set";
}
?>
<div id="popup2" class="overlay">
<div class="popup">
<h2 class="range2">Edit</h2>
<a class="close" href="#">×</a>
<div class="content">
<?php foreach ($msg as $value) {
echo $value."<br>";
}?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php if(isset($data)){?>
<input class="input" type="hidden" name="id" value="<?php echo $data['id']; ?>" />
<?php } ?>
<input class="input" type="text" name="nim" value="<?php echo isset($data)?$data['nim']:''?>" placeholder="NIM" required/>
<input class="input" type="text" name="name" value="<?php echo isset($data)?$data['name']:''?>" placeholder="Name" required/>
<i>SK</i>
<input class="input1" type="text" name="class1" value="<?php echo isset($data)?$data['class1']:''?>" placeholder="00" required/>
<i>-</i>
<input class="input1" type="text" name="class2" value="<?php echo isset($data)?$data['class2']:''?>" placeholder="00" required/>
<input name="update" type="submit" class="button" id="submit" value="Submit">
</form>
</div>
</div>
</div>
My friend,
only do one thing to resolve this
echo $result = "UPDATE users SET nim='$nim', name='$name', class1='$class1', class1='$class1' WHERE id='$id'";
die;
then submit your form again and you will get your static query into your page then just copy that query and try to run into phpmyadmin then you will get your actual error.
Ok i have updated my Code, not getting any Errors but nothing is being updated on the mysql side nor on the PHP Front end.
I have even tried a Hard Coded Statment.
This section is at the Very top of my Php Viewer page..
<?php
/
/ IF RESQUEST IS EQUAL TO SUBMUIT
if (isset($_REQUEST['submit']))
{
$my_date = date("Y-m-d H:i:s");
$order = uniqid();
$FullName= $_REQUEST['fullname'];
//Take in full Name and Split it into first and last name.
list($fname, $lname ) = explode( ' ', $customerName, 2 );
$address = $_REQUEST['address'];
$emailAddress = $_REQUEST['emailAddress'];
$phoneNo = $_REQUEST['phoneNo'];
Below is my Sticky Forum which is getting the Information from the Database and putting it into the Text Fields
// STICKY FORM TO ALLOW USER TO UPDATE INFORMATION
if (isset($_REQUEST['up']))
{
$query_sticky = mysqli_query($connection,'SELECT * FROM orders WHERE id = "' . $_GET['id'] . '"');
if(! $query_sticky )
{
die('Could not get data: ' . mysqli_error($connection)); // Could not find Order_id show Error
}//end die error
else
(isset($_REQUEST['update']));
{
while($row = mysqli_fetch_array($query_sticky, MYSQLI_ASSOC))
{
$row['id'];
echo '<form action="" method="post">'
Name:';
echo'<input name="customerName" id="cname" type="text" required value="'.$row['firstname']. " " .$row['lastname']. '" />';
echo' <br/>
<br/>
Address:
<textarea name="address" id = "caddress" type="text" rows="5" cols="30" required value="'.$row['address'].'" ></textarea>
<br/>
<br/>
Email Address:
<input name="emailAddress" type="email" required value="'.$row['email']. '" />
<br/>
<br/>
<br/>
Phone Number:
<input name="phoneNo" id="phoneNumber" type="text" required value="'.$row['phone']. '" />
<br/>
<br/>
<button type="submit" name="update" value="update" >update</button
<div id="Submit">
</form>
<form action="order.php" method="delete">
</form>';
}//close if
}
} // Close While
here is my Update Section
if (isset($_REQUEST['update']))
{
$updateDB = "UPDATE orders SET student ='$_POST[student]',
firstname='John', lastname='wallace',
email = '$_POST[emailAddress]', address = '$_POST[address]',
phone = '$_POST[phoneNo]'
WHERE
order_id ='$_GET[order_id]'";
mysqli_query($connection, $updateDB);
}//end update..
}//end PHP
?>
You were mixing up single and double quotes in your UPDATE query string. Try this instead:
$updateDB = "UPDATE test
SET email = '".#$_POST[$emailAddress]."',
address = '".#$_POST[$address]."',
phone = '".#$_POST[$phoneNo]."'
WHERE id = '".$_GET['id']."'";