storing text in different rows of MySQL database based on newline - php

The HTML code is below:
<div class="form-data">
<form method="POST" action="test_upload_file.php" enctype="multipart/form-data">
ID:<br>
<input type="text" name="id"><br>
Quote:<br>
<textarea rows="4" cols="30" name="text-file"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>
</div>
The corresponding php code is below:
<?php
//connect database
$conn = mysqli_connect("localhost","root","","androidtest");
if (isset($_POST['submit'])) {
$quote_id = $_POST['id'];
$text = $_POST['text-file'];
//insert data
$sql = "INSERT INTO quotes (quote_id, quote) VALUES ('$quote_id', '$text')";
//store in the table
$insert = mysqli_query($conn, $sql);
if ($insert) {
echo "Success.";
} else {
echo "Error.";
}
//close mysql connection
mysql_close($conn);
//won't resubmit the form
header("Location: " . $_SERVER['REQUEST_URI']);
}
?>
I want to post multiple sentences separated by break in textarea. They should be stored in different rows in MySQL database.
For eg, if i put an id of 2 and post a text having multiple sentences separated by break or newline, then it should store in the database like this:
quote_id quote
2 line 1
2 line 2
2 line 3

Try following code, it may help you. I am not sure the textarea next line seperated by '\n'. Please make sure that
//connect database
$conn = mysqli_connect("localhost","root","","androidtest");
if (isset($_POST['submit'])) {
$quote_id = $_POST['id'];
$get_file = $_POST['text-file'];
$textArray = explode("\n", $get_file);
foreach($textArray as $key=>$value) {
//insert data
$sql = "INSERT INTO quotes (quote_id, quote) VALUES ('$quote_id', '$value')";
//store in the table
$insert = mysqli_query($conn, $sql);
if ($insert) {
echo "Success.";
} else {
echo "Error.";
}
}
//close mysql connection
mysql_close($conn);
//won't resubmit the form
header("Location: " . $_SERVER['REQUEST_URI']);
}

Related

Cannot add post and images value into database

i'm trying to add text and images using
Image is successfully added into folder path. but the value of text and images did not add into database
<?php
function insertpost(){
global $connect;
if(isset($_POST['sendpost']))
{
$title = mysqli_real_escape_string($connect,$_POST["title"]);
$target_image = "images/".basename($_FILES['post_image']['name']);
$post_image = $_FILES['post_image']['name'];
$insert_post_and_image = "INSERT INTO table(title, image) VALUES ('$title','$post_image')";
mysqli_query($connect, $insert_post_and_image);
if(move_uploaded_file($_FILES['post_image']['tmp_name'], $target_image))
{
echo "<h3>Posted to timeline!</h3>";
}
}
}
?>
html code
<form action="" method="post" id="form" enctype="multipart/form-data">
<input type="text" name="title"/>
<input type="file" name="post_image"/>
<input type="submit" name="sendpost" value="POST"/>
</form>
any solution? thanks
I think you have mistake in table name in your query .Just replace table with your actual table name.For example if you have defined table name as user then your query must be
$insert_post_and_image = "INSERT INTO user(title, image) VALUES ('$title','$post_image')";
Also you can check error using
if (mysqli_query($connect, $insert_post_and_image)) {
echo "success";
} else {
echo "Error: " . mysqli_error($connect);
}
*correction
Hi, already found the answer . i'm not sure if it's correct or not . please advise. thanks :)
<?php
function insertpost(){
global $connect;
if(isset($_POST['sendpost']))
{
$title = mysqli_real_escape_string($connect,$_POST["title"]);
$target_image = "images/".basename($_FILES['post_image']['name']);
$post_image = $_FILES['post_image']['name'];
$insert_post_and_image = "INSERT INTO table(title, image) VALUES ('$title','$post_image')";
$result = mysqli_query($connect, $insert_post_and_image);
if($result)
{
move_uploaded_file($_FILES['post_image']['tmp_name'], $target_image);
echo "<h3>Posted to timeline!</h3>";
}
}
}
?>

How to UPDATE only filled input with a submit button?

PROBLEM: I got a problem updating my input into sql using PHP, the PHP updates all empty values into sql which I don't want to.
ACHIEVEMENT: So I hope to achieve when user submit their data either empty or filled then PHP might be able to pickup and update only filled data into my sql. I tried using input with value=">php echo here<" but it won't work with textarea, so I couldn't find any solution since I'm new to PHP and SQL. Tried to find similar posts but I couldn't make them work like I wanted to :(
<?php include 'config/sqlconnect.php'; ?>
<form method="post" action"config/sqlconnect.php">
</p>MainPage info</p>
<input type="text" name="mainPageInfo"/>
<br>
</p>MiddlePage info</p>
<textarea name="middlePageInfo"></textarea>
<br>
</p>Container info</p>
<input type="text" name="containerInfo"/>
<br>
</p>Content</p>
<input type="text" name="content"/>
<br>
</p>Second content</p>
<input type="text" name="secondContent"/>
<input type="submit" name="submit" class="btn-block"/>
<br>
</form>
in PHP script
<?php
$servername = "localhost";
$username = "root";
$password = "pass";
$dbname = "pagesDb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_set_charset($conn,"utf8");
$sql = "SELECT * FROM myPages";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$mainPageInfo = $row['mainPageInfo'];
$middlePageInfo = $row['middlePageInfo'];
$containerInfo = $row['containerInfo'];
$content = $row['content'];
$secondContent = $row['secondContent'];
}
} else {
echo "0 results";
}
if (isset($_POST['submit'])) {
$mainPageInfo = $_POST['mainPageInfo'];
$middlePageInfo = $_POST['middlePageInfo'];
$containerInfo = $_POST['containerInfo'];
$content = $_POST['content'];
$secondContent = $_POST['secondContent'];
$sql = "UPDATE myPages SET mainPageInfo='$mainPageInfo',
middlePageInfo='$middlePageInfo',
containerInfo='$containerInfo',
content='$content',
secondContent='$secondContent'
WHERE id=0";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
$conn->close();
?>
Second Attempts: It doesn't update my data somehow... please help I tried more than 8 hours with no results :(
if (isset($_POST['submit'])) {
foreach($_POST as $name => $value) {
$sql = "UPDATE myPages SET $name = '$value' WHERE id=1";
}
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
Help would be appreciated, thanks everyone!
Using your Second Attempt as a starting point.
The problem with just using the POST array without being specific is that, in this example you are going to try an update a column on the database called submit i.e. your submit button. Later there may be data on the page that belongs in 2 or more tables.
So create an controlling array containing all the field names from the form that you want to process onto your table.
$db_fields = array('mainPageInfo', 'middlePageInfo', 'containerInfo',
'content', 'secondContent');
$sql = ''; // will hold the query we build dynamically
// was this a user sending data
if ( $_SERVER['REQUEST_METHOD' == 'POST' ) {
foreach($db_fields as $fieldname) {
if ( ! empty($_POST[$fieldname] ) {
$sql .= "$fieldname = '{$_POST[$fieldname]}', ";
}
}
}
$sql = rtrim($sql, ','); // remove the trailing comma
$sql = "UPDATE myPages SET $sql WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

POST Data not inserting into sql table

I am using a form. (I wanted the message text as a text area but changed back to normal text to see if this was the problem)
This is the form I am using
<form name="addmessage" method="POST" action="addmessage.php" >
<input type="text" name="message_title" id="message_title">Message Title</input>
<input type="text" name="message_text" id="message_text">Message</input>
<input type="submit" name="submit" value = Add>
</form>
Below is the PHP code. I understand i need to protect against sql injection however, i can do this later.
<?php
include_once("config.php");
if(isset($_POST["message_title"]) && strlen($_POST["message_title"])>0)
{
$message_title=$_POST['message_title'];
$message_text=$_POST['message_text'];
session_start();
$barber_id = $_SESSION['barber_id'];
$insert_row = $mysqli->query("INSERT INTO messages(barber_id,message_title,message_text) VALUES('".$barber_id."','".$message_title."',".$message_text.")");
}
else
{
//Output error
header('HTTP/1.1 500 Error You have left it blank');
exit();
}
header("location:messages.php");
?>
If manually enter data using phpMyAdmin, I can get it to display using the code below.
include_once("config.php");
session_start();
$barber_id = $_SESSION['barber_id'];
$results = $mysqli->query("SELECT * FROM messages WHERE barber_id ='$barber_id' ");
//get all records from table
while($row = $results->fetch_assoc())
{
$prices_id = $row['prices_id'];
echo '<div data-role="collapsible">';
echo '<h1>';
echo ' Message Title: ';
echo $row['message_title'];
echo '</a>';
echo '</h1>';
echo '<p>';
echo $row['message_text'];
echo ' Delete</div>';
}
$mysqli->close();
?>
At $insert_row = $mysqli->query("INSERT INTO messages(barber_id,message_title,message_text) VALUES('".$barber_id."','".$message_title."',".$message_text.")");
you should write
$insert_row = $mysqli->query("INSERT INTO messages(barber_id,message_title,message_text) VALUES('".$barber_id."','".$message_title."','".$message_text."')");
Everytime you pass a String or other non int values you must pass them like that: 'xx', otherwise mysql will see it as query param and it crashes.

Trying to create a simple cumulative addition script in PHP (or JS):

Trying to create a simple cumulative addition script in PHP (or JS):
1) enter any integer(4 digits or less), click submit, number entered is displayed and saved on the same web page
2) enter another number, click submit, number entered is added to previous number and total is saved and displayed on the web page
Repeat …….
Example: the mantra counter at garchen.net
Below is the code I have so far
In Index.php:
<form method="post" action= "process-mantra-form-ami.php" >
<p><strong>Amitabha Million Mantra Accumulation: </strong><br></p>
<div style="margin-left: 20px;">
<p>OM AMI DEWA HRI</p>
<input type="text" name="accumulation" size="10" maxlength="6">
<input type="submit" value="Submit Your Mantra" name="B1"><br>
<span id="mani">Amitabha Mantra Count: <?php echo $newValue; ?> </span>
<p></p>
</div>
</form>
I am getting confused about the form processing php. Im attempting to use my local mamp server for the db. Do I create a connection, create a database, and a table, insert form data into table, and retrieve data back to index.php all at the same time in the process-mantra-form-ami.php file?
You guys made it seem easy in my last post, but there seems to be a lot to it. I know my code below is incomplete and not quite correct. Help!
PROCESS-MANTRA-FORM-AMI.PHP code below
<?php
// Create connection
$con=mysqli_connect("localhost:8888","root","root","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$accumulation = mysqli_real_escape_string($con, $_POST['accumulation']);
// Create database
$sql="CREATE DATABASE my_db";
if (mysqli_query($con,$sql)) {
echo "Database my_db created successfully";
} else {
echo "Error creating database: " . mysqli_error($con);
}
// Create table "Mantras" with one column 'Num'
$sql="CREATE TABLE Mantras (Num INT)";
if (mysqli_query($con,$sql)) {
echo "Table mantras created successfully";
} else {
echo "Error creating table: " . mysqli_error($con);
}
// Insert form data into table
$sql="INSERT INTO Mantras (Num INT)
VALUES ('$num')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
// update database
mysqli_query($con,"UPDATE Mantra SET Num = num + 1");
}
mysqli_close($con);
?>
<div>
<h2>Thank you for your <?php echo $num; ?> Amitabha Mantras!</h2>
<p>Remember to dedicate your merit.</p>
<p>Return to the main site</p>
</div>
try this out... (sorry, bored tonight)
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
$conn->query($sql)
$conn->prepare($sql)
$conn->error
http://php.net/manual/en/class.mysqli-stmt.php
$stmt->bind_param('ss',$val1,$val2)
$stmt->bind_result($res1,$res2)
http://php.net/manual/en/mysqli.construct.php
<?php
$host = 'localhost'; // localhost:8888
$user = 'root';
$pass = ''; // root
$dbnm = 'test';
$conn = mysqli_connect($host,$user,$pass,$dbnm)
or die('Error ' . $conn->connect_error);
// for testing.... so i can run the code over and over again and not
// get errors about things existing and stuff
run_statement($conn,"drop database if exists `my_db`;",'cleared old db');
run_statement($conn,"drop table if exists `mantras`;",'cleared old table');
run_statement($conn,"drop table if exists `two_col_table`;",'cleared old table');
// Create database
$sql = 'create database my_db';
$err = run_statement($conn,$sql,'Database creation');
if (!$err) $conn->select_db('my_db');
// Create table "Mantras" with one column 'Num'
$sql = 'create table mantras (num int)';
$err = run_statement($conn,$sql,'Table mantras');
if (!$err) {
$sql = 'insert into mantras (num) values ( ? )';
$stmt = $conn->prepare($sql);
$stmt->bind_param('d',$num); // d is for digit but s (string) would work too
$num = 1;
$stmt->execute();
$num = 2;
$stmt->execute();
$stmt->close();
echo ($conn->error) ? "insert errored: {$conn->error}" : 'insert ran succesfully';
// update database
$sql = 'update mantras set num = num + 1';
run_statement($conn,$sql,'Update database');
}
// Create table "test" with two columns
$sql = 'create table two_col_tbl (num int, txt varchar(10))';
$err = run_statement($conn,$sql,'Table two_col_tbl');
if (!$err) {
// demonstrating how to bind multiple values
$sql = 'insert into two_col_tbl values ( ?, ? )';
$stmt = $conn->prepare($sql);
$stmt->bind_param('ds',$num,$txt);
$num = 1; $txt = 'hello';
$stmt->execute();
$num = 2; $txt = 'world';
$stmt->execute();
$stmt->close();
// select statement
$sql = 'select num, txt from two_col_tbl';
$stmt = $conn->prepare($sql);
$stmt->bind_result($db_num, $db_txt);
$stmt->execute();
print '<table><tr><th colspan=2>two_col_tbl</tr><tr><th>num</th><th>txt</th></tr>';
while ($stmt->fetch()) {
print "<tr><td>$db_num</td><td>$db_txt</td></tr>";
}
print '<table>';
$stmt->close();
}
$conn->close();
function run_statement($conn,$statement,$descr) {
if ($conn->query($statement))
echo "$descr ran successfully";
else echo "$descr failed: {$conn->error}";
return $conn->error;
}
?>
<div>
<h2>Thank you for your <?php echo $num; ?> Amitabha Mantras!</h2>
<p>Remember to dedicate your merit.</p>
<p>Return to the main site</p>
</div>

connection table for overcoming the checkbox problem

i have a php form with text box,radiobutton and checkboxes.I have connected it to the databse , the values are getting stored into the database except the checkbox values.I want to enter all the checkbox values into the database.I want an backend such that it links to two tables.the text box and the radio button values are to be stored in the first table and the id's of the selected checkbox values in the other table.
u can store only that value in database which is checked, but you can not store all value of check box with same name attribute, because by checking that checkbox, that value is proceed to next page via POST/GET
but if u want all value of check box ( multiple check box) then use name array like below
<form action="checkbox.php" method="post">
<input type="checkbox" name="checkbox[]" value="a">
<input type="checkbox" name="checkbox[]" value="b">
<input type="checkbox" name="checkbox[]" value="c">
<input type="checkbox" name="checkbox[]" value="d">
<br>
<br>
<input type="submit" name="Submit" value="Submit">
</form>
<?
/* and in your checkbox.php you do this: */
if(isset($_POST['Submit']))
{
for ($i=0; $i<count($_POST['checkbox']);$i++) {
echo "<br />value $i = ".$_POST['checkbox'][$i];
}
}
?>
a connection table can be created (i.e A single php page connection is given to two tables of the same database)the code ia as follows. this code should be given as backend to the php page.
$dbhost = "localhost:3306"; // usually is localhost, but if not sure, check with your hosting company, if you are with webune leave as localhost
$dbuser = "root"; // change to your database password
$dbpass = "mysql"; // change to your database password
$dbname = "probe_config"; // provide your database name
$db_table = "mapping"; // leave this as is
$conn = mysql_connect("$dbhost", "$dbuser", "$dbpass");
$select = mysql_select_db("$dbname");
//selecting the urls
$selected = $_POST['urlSelect'];
if (count($selected) > 0)
{
for ($i=0;$i<count($selected);$i++) {
echo "$selected[$i] <br />";
}
}
$timeout=$_POST['timeout'] ;
$wait=$_POST['wait'];
$clearcache=$_POST['clearcache'];
$name=$_POST['name'];
$replication=$_POST['replication'];
//inserting into the databse
$query = "INSERT INTO webmeasurementsuite (wait, timeout, clearcache, name, replication)
values ($wait, $timeout, '$clearcache', '$name', $replication)";
if (!mysql_query($query,$conn))
{
die('Error: ' . mysql_error());
}
else
{
echo "1 record added to WMS";
$query = "SELECT wms_id FROM webmeasurementsuite ORDER BY wms_id DESC LIMIT 1";
if (!($result=mysql_query($query,$conn)))
{
die('Error: ' . mysql_error());
}
else
{
$row = mysql_fetch_assoc($result);
$id=$row['wms_id'];
$selected = $_POST['urlSelect'];
if (count($selected) > 0)
{
for ($i=0;$i<count($selected);$i++) {
$urlentry=$urlentry.", ";
if($i==0)
{
$urlentry="";
$j++;
}
$urlentry=$urlentry .$selected[$i];
}
}
echo $urlentry;
echo '<br />id='.$id;
//insert for the second table
$query= "INSERT INTO mapping(wms_Id, wm_Id) values ($id, '$urlentry')";
if (!mysql_query($query,$conn))
{
die('Error: ' . mysql_error());
}
else
{
echo "Mapping Done";
}
}
}
mysql_close($conn);
?>

Categories