I'm having a challenge with a mini project I'm working on and have googled for a solution for hours without a headway.
I have a column in my database table whose contents are generated by exploding a previous form inputs(separated by comma in the table). Now I need to get inputs (from users) for these values using textarea in a form. These inputs will be in arrays depending on the number of contents fetched from the db in the first place and then stored in another column in my table. The issue here is that each time I submit the form I get an undefined index notice for the name of the values in the textarea field, which is test-col [].
please see my code below:
<?php
$conn = mysqli_connect('localhost', 'root', '', 'myDb');
$users_id = mysqli_real_escape_string($conn, $_GET['id']);
$res = mysqli_query($conn, "SELECT tests FROM bal WHERE users_id = '$users_id'");
if ($res){
while ($row = mysqli_fetch_array($res)){
$tests = explode(',', $row['tests']);
foreach($tests as $test){
if ($test ==""){
continue;
}
echo '<div class="test-res" style="margin-top:10px;">
<form action="" method="post" role="form" class="form-horizontal">
<div class="form-group">
<label for= "test-col" class="form-label col-md-2">'.$test.' test</label>
<div class="col-md-10">
<textarea class="form-control" rows="3" name="test-col[]" placeholder="Test result"> </textarea>
</div>
</div>
</form>
</div>';
'<br /> <br />';
}
}
}
echo '<form action="" method="post">
<button type="submit" class="btn btn-success col-md-offset-5" name="sub-res">Send Result</button>
</form>';
?>
//to insert textarea values in db
<?php
if(isset($_POST['sub-res'])){
$conn = mysqli_connect('localhost', 'root', '', 'myDb');
foreach ($_POST ['test-col'] as $values){
$test_results = implode("<br>", $values);
}
$ins = mysqli_query($conn, "INSERT INTO bal (results) VALUES
('$test_results') WHERE users_id = '$users_id'");
if (!$ins){
die(mysqli_error());
}
else{
echo '<div class="alert alert-success">Successfully sent</div>';
}
}
?>
You have two forms - one in your while/foreach statement, and then one below. If you're submitting the second form, it won't contain values from the first.
Wrap the while in the form instead;
<form action="" method="post">
<?php
$conn = mysqli_connect('localhost', 'root', '', 'myDb');
$users_id = mysqli_real_escape_string($conn, $_GET['id']);
$res = mysqli_query($conn, "SELECT tests FROM bal WHERE users_id =
'$users_id'");
if ($res){
while ($row = mysqli_fetch_array($res)){
$tests = explode(',', $row['tests']);
foreach($tests as $test){
if ($test =="") {
continue;
}
echo '<div class="test-res" style="margin-top:10px;"><div class="form-group">
<label for= "test-col" class="form-label col-md-2">'.$test.' test</label><div class="col-md-10"><textarea class="form-control" rows="3" name="test-col[]" placeholder="Test result"> </textarea></div></div></div>';
'<br /> <br />' ;
}
}
}
?>
<button type="submit" class="btn btn-success col-md-offset-5" name="sub-res">Send Result</button>
</form>
Related
How best can I save a select option value name instead of the id using just Ajax, PHP and MYSQL.
I tried many ways but for now when I select the data and store back it keeps saving generated id and that's not what I want.
When i decided to change the id of the selection option to value i the values does show on the drop down.
Details.php
<form method="post" name="signup" onSubmit="return valid();">
<label class="control-label">Profile ID</label>
<select id="employee" name="regcode" class="form-control">
<option value="" selected="selected">Select Profile ID</option>
<?php
$sql = "SELECT id,regcode FROM tbstudentprofile";
$query = $dbh->prepare($sql);
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
?>
<option name="regcode" value="<?php echo $row["id"]; ?>">
<?php echo $row["regcode"]; ?> </option>
<?php } ?>
</select>
<div class=" form-group1 form-last>
<label class=" control-label">Status</label>
<textarea name="status" row="2"></textarea>
</div>
<button type="submit" name="save">Save </button>
</form>
enter code here
query
if (isset($_POST['save'])) {
$regcode = $_POST['regcode'];
$status = $_POST['status'];
$sql = "INSERT INTO studentschooltbl(regcode,status) VALUES(:regcode,:status)";
$query = $dbh->prepare($sql);
$query->bindParam(':regcode', $regcode, PDO::PARAM_STR);
$query->bindParam(':status', $status, PDO::PARAM_STR);
$query->execute();
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$lastInsertId = $dbh->lastInsertId();
if ($lastInsertId) {
$msg = " Registration successfully";
} else {
$error = "error";
}
}
I wrote the code below. When I pass $cat_title in myslqi and i print $query it runs the query but in mysql table cat_title field is empty.
<?php
if(isset($_POST['submit'])){
$cat_title = $_POST['cat_title'];
echo "this is cat_title: ".$cat_title."<br>";
if($cat_title ="" ){
echo "title shouldn't be empty";
}
else{
echo $cat_title."this is cat_tiltel";
$query = "INSERT INTO categories(cat_title) ";
$query .= "VALUE('{$cat_title}') ";
echo $query;
$create_category_query = mysqli_query($connection , $query);
if(!$create_category_query){
die("QUERY FAILD".mysqli_error($connection));
}
header("location:categories.php");
}
}
?>
<form action="" method="post">
<div class="form-group">
<label for="cat-title">category title</label>
<input class="form-control" type="text" name ="cat_title">
</div>
<div class="form-group">
<input class = type="submit" name ="submit" value ="Add category">
</div>
</form>
There is a typo error. Please write "VALUES". You have written just VALUE.
Plese try to use below sintex.
INSERT INTO `table_name`(column_1,column_2,...) VALUES (value_1,value_2,...);
I am very new to PHP and HTML. I am trying to fetch the row value from input form data, but i am unable to fetch the data.
Below is my code.
HTML:
<form id="main" action="test.php" method="post" enctype="multipart/form-data" >
<div class="row">
<div class="col-md-12">
<label for="model" style="font-size: 15px"> Model </label><br>
<input type="text" id="tags" name="model" placeholder="Type Your Model Number" >
</div>
</div>
<div class="row">
<div class="col-md-12">
<button type="submit" id="button" name="submit1" />SUBMIT</button>
</div>
</div>
</form>
</html>
PHP CODE:
<?php
if(isset($_POST['submit']))
{
// id to search
$model = $_POST['model'];
// connect to mysql
$connect = mysqli_connect("localhost", "root", "","test");
// mysql search query
$query = "SELECT `offer`, `amount` FROM `offer`";
$result = mysqli_query($connect, $query);
// if id exist
// show data in inputs
if(mysqli_num_rows($result) > 0)
{
while ($row = mysqli_fetch_array($result))
{
$offer = $row['offer'];
$amount = $row['amount'];
}}
if($model){
echo "
<form method='post' action=''>
<div class='col-md-5'>
$offer
</div>
<div class='col-md-5'>
INR $amount/-
</div>
</div></form>";
else {
$offer = "";
$amount = "";
$offer2 = "";
$amount2 = "";
}
mysqli_free_result($result);
mysqli_close($connect);}
else{
$offer = "";
$amount = "";
$offer2 = "";
$amount2 = "";
}
?>
Also, please note that the model is alphanumeric. Offer would be Headset and amount would be 100. I request to help me on this.
First of all we don't know what your error is and second you haven't included all your code. However, for PHP use following code
<?php
$mysqli = new mysqli("localhost", "root", "", "test") or die($mysqli->error);
$select = $mysqli->query("SELECT * from offer") or die($mysqli->error);
if($select->num_rows){
while($row = $select->fetch_array(MYSQLI_ASSOC)){
$amount = $row['amount'];
$offer= $row['offer'];
}
}
?>
You have used input and button but i don't see any form tags in HTML
You have to pass the $model in your query and do that to show the results:
echo "<form method='post' action=''>";
while ($row = mysqli_fetch_array($result))
{
echo " <div class='col-md-5'>
".$row['offer']."
</div>
<div class='col-md-5'>
INR ".$row['amount']."-
</div> ";
}
echo "</form>";
This is my first post in this forum, despite being a devoted follower for years now.
I have built a simple system that registers lot numbers and their locations within a MySQL database through a PHP form.
Then i have this other form called "Errata Corrige" that I use to find and edit eventual mistaken entries.
It's search criteria is an (UNSIGNED INT UNIQUE) value named "lotto" and everything works (worked) like a charm under this circumstances.
Now the thing got a little tricky.
I found out that lot numbers (lotto) for work purposes are not always unique values, there might be more than one entry with the same number.
No problem making the "Insert" form or various counters work under this new circumstances, but it got really tricky within the EDIT functions.
This is my PHP code: `
<?php
$id = "";
$settore = "";
$ubicazione = "";
$numero = "";
$lotto="";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// connect to mysql database
try{
$connect = mysqli_connect($host, $user, $password, $database);
} catch (mysqli_sql_exception $ex) {
echo 'Error';
}
// get values from the form
function getPosts()
{
$posts = array();
$posts[0] = $_POST['id'];
$posts[1] = $_POST['settore'];
$posts[2] = $_POST['ubicazione'];
$posts[3] = $_POST['numero'];
$posts[4] = $_POST['lotto'];
return $posts;
}
// Search
if(isset($_POST['search']))
{
$data = getPosts();
$search_Query = "SELECT * FROM mappa WHERE lotto = $data[4]";
$search_Result = mysqli_query($connect, $search_Query);
if($search_Result)
{
if(mysqli_num_rows($search_Result))
{
while($row = mysqli_fetch_array($search_Result))
{
$id = $row['id'];
$settore = $row['settore'];
$ubicazione = $row['ubicazione'];
$numero = $row['numero'];
$lotto = $row ['lotto'];
}
}else{
echo 'Lotto non presente in archivio';
}
}else{
echo 'Error';
}
}
// Insert
if(isset($_POST['insert']))
{
$data = getPosts();
$insert_Query = "INSERT INTO `mappa`(`settore`, `ubicazione`, `numero`, `lotto` ) VALUES ('$data[1]','$data[2]',$data[3], $data[4])";
try{
$insert_Result = mysqli_query($connect, $insert_Query);
if($insert_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
$resInsert = "1 nuovo dato inserito correttamente!";
}else{
$resInsert = "Nessun dato inserito";
}
}
} catch (Exception $ex) {
echo 'Errore '.$ex->getMessage();
}
}
// Edit
if(isset($_POST['update']))
{
$data = getPosts();
$update_Query = "UPDATE `mappa` SET `settore`='$data[1]',`ubicazione`='$data[2]',`numero`=$data[3],`lotto`=$data[4] WHERE `id` = $data[0]";
try{
$update_Result = mysqli_query($connect, $update_Query);
if($update_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
$resAgg = "1 dato aggiornato correttamente!";
}else{
$resAgg = "Nessun dato aggiornato!";
}
}
} catch (Exception $ex) {
echo 'Error Update '.$ex->getMessage();
}
} ?>
`
HTML:
<form action="mod.php" method="post" class="form-horizontal form-bordered" style="text-align:center">
<div class="form-group has-error" style="padding-top:30px">
<label class="col-xs-3 control-label" for="state-normal">ID</label>
<div class="col-lg-3">
<input type="text" name="id" placeholder="ID" class="form-control" value="<?php echo $id;?>"> </div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="state-normal">Settore</label>
<div class="col-md-6">
<input type="text" name="settore" placeholder="Settore" class="form-control" value="<?php echo $settore;?>"> </div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="state-normal">Ubicazione</label>
<div class="col-md-6">
<input type="text" name="ubicazione" placeholder="Ubicazione" class="form-control" value="<?php echo $ubicazione;?>"> </div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="state-normal">Numero</label>
<div class="col-md-6">
<input type="text" name="numero" placeholder="Numero" class="form-control" value="<?php echo $numero;?>"> </div>
</div>
<div class="form-group has-success">
<label class="col-md-3 control-label" for="state-normal">Lotto</label>
<div class="col-md-6">
<input type="text" name="lotto" placeholder="Lotto" class="form-control" value="<?php echo $lotto;?>"> </div>
</div>
<div style="padding-top:16px">
<!-- Insert-->
<button type="submit" name="insert" value="Add" class="btn btn-effect-ripple btn-primary">Inserisci</button>
<!-- Update-->
<button type="submit" name="update" value="Update" class="btn btn-effect-ripple btn-info">Aggiorna</button>
<a> </a>
<!-- Search-->
<button type="submit" name="search" value="Find" class="btn btn-effect-ripple btn-success">Cerca</button>
</div>
</form>
While the lot number was unique everything worked like a charm.
Now that there are multiple data with the same lot number the code became obsolete since the "search" function only shows the last (greatest ID) data.
I have tried to work around a loop and tell the function to search every ID where lotto = lotto but it didn't work.
A simple solution would be obviously searching through ID instead of lotto but that is a pretty crapy one, since the user only knows (and is interested in) Lot Numbers not the ID it was assigned during data insertion.
Then I tried to put two php functions into one page, the first that fetches data from Mysql into a PHP dropdown menu, telling it to show every ID that matches the search criteria (lotto):
<?php if (isset($_POST['submitted'])){
include ('../mysql_connect.php'); // connessione al database
$category = 'lotto';
$criteria = $_POST['criteria'];
$query = "SELECT * FROM mappa WHERE $category = '$criteria'";
$result = mysqli_query($dbcon, $query) or die('Impossibile reperire i dati');
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$idTab = $row['id'];
echo "<option>
$idTab </option>";
}
} // FINE if ?>
</select>
Fetching data from MySQL into the dropdown worked just fine, but I got stucked in the syntax trying to use this dropdown as a search criteria for my first function.
Every help would really be appreciated! Thank you in advance for your answers.
You said that lotto is unique. So how come you are able to insert multiple rows with the same lotto?
Remove the unique constraint from the lotto column.
Try the following:
$query = select lotto, group_concat(id) as ID numbers from mappa where lotto = 'user search number' group by lotto;
$result = $conn->query($query);
$rows = $result->num_rows;
$result->data_seek(0); //move to first row (which is the only one)
$row = $result->fetch_array(MYSQLI_NUM); //fetch array
$id_numbers_string = $row[1]; //store the values of the row's second column (which is number 1)
$id_numbers_separated_array = explode(",", $id_numbers_string); //create an array with the values in the string
for($i = 0; $i < count($id_numbers_separated_array); $i++){ //loop through created array
echo "ID: " . $id_numbers_separated_array[$i];
echo "<br>";
}
Also try to run the query in your database management system to see the results.
i'm a bit of PHP noob, so sorry if this is a daft question, but I just can't figure this out by myself so any help would be greatly appreciated!
I am trying to create a modify page for an events web application. It seems to be working except when I try to validate the final if/else statement.
This statement returns the value of $row[0] and checks if its == NULL. If NULL, it should return an echo 'this event does not exist' to the user, if there is a value, it presents the user with a matrix of text boxes that they can change the data in.
Currently it works fine for the else statement when there is data found, but doesnt recognise the original if when there is no data. Coupled with that, the footer at the bottom of the page disappears!
Here is the main body of the code, i have highlighted the problem area. I understand that there is probably a more effective and efficient way of doing it all, but please keep it simple as I'm still learning. Thanks again. Dan
<div class="round">
<div id="main" class="round">
<span class="bold">MODIFY EVENT</span><br /><br />
On this page you can modify or delete the events that are stored on the database.<br />
Be aware that you cannot undo the DELETE function.<br />
<br />
Find Event:<br />
<table>
<form name="form1" id="form1" method="post" action="
<?php echo $_SERVER["PHP_SELF"]; ?>" >
<tr><th>By Date:</td><td><input type="text" name="modifyDate"
id="modifyDate" value="dd/mm/yy" /></td></tr>
<tr><th>By Name:</td><td><input type="text" name="modifyName" id="modifyName"
value="" /></td></tr>
<tr><th>Find All:</th><td><input type="checkbox" name="modifyAll"
id="modifyAll" /><td></tr>
<tr><td></td><td><input type="submit" name="submit" value="Search" /></td></tr>
</form>
</table>
<?PHP
if(!isset($_POST['modify'])){
if(isset($_POST['submit'])){
$moddate = $_POST['modifyDate'];
If($moddate == "dd/mm/yy"){
$date = "";
}
else{
$newDate = str_replace("/",".",$moddate);
$wholeDate = $newDate;
$dateArray = explode('.', $wholeDate);
$date = mktime(0,0,0,$dateArray[1],$dateArray[0],$dateArray[2]);
}
$name = $_POST['modifyName'];
$all = $_POST['modifyAll'];
$host = "localhost";
$user = "user";
$password = "password";
$db = "database";
$con = mysql_connect($host,$user,$password) or die('Could not connect to Server');
$dbc = mysql_select_db($db, $con) or die('Could not connect to Database');
if($all != 'on'){
$q = "SELECT * FROM events WHERE date = '$date' || title = '$name' ";
}
else{
$q = "SELECT * FROM events";
}
$result = mysql_query($q);
$row = mysql_fetch_array($result) or die(mysql_error());
//THIS IS THE PROBLEM HERE!!!!
if($row[0]==NULL){
echo 'This event does not exist';
}
else{
?>
<form name="form1" id="form1" method="post" action="
<?phpecho $_SERVER['PHP_SELF']; ?>" >
<?PHP
$result = mysql_query($q) or die(mysql_error());
while ($row = mysql_fetch_array($result)){
$initialDate = date('d/m/y', $row['date']);
$ID = $row['ID'];
echo '<input type="text" name="inputEmail" id="inputEmail" value="'.$initialDate.'" />';
echo '<input type="checkbox" value=$ID name="toModify[]" style = "visibility: hidden;" /><br /><br />';
}
echo '<input type="submit" name="modify" value="Modify" />
<br /><br />';
}
}
}
else{
//modify database and return echo to user
}
?>
</div>
<div id="clear"></div>
</div>
</div>
</div>
<div id="footer" class="round shadow"></div>
</body>
</html>
mysql_fetch_array($result) returns false if there are no rows, so it's possible that even if there is nothing in the result, it's still returning a false and your if($row[0] == null) is evaluating to false, also.
In other words, you should be doing a more robust test on the return results from your query to catch fringe cases.
As others have mentioned or implied, here are some things you could / should be doing:
test for rows returned, not values in rows
test for existence of variable, not content of variable
check the database for errors returned
Is the field in the table it's pulling $row[0] from set to NOT NULL? If it is, it will never be a null value. Try instead something like (if empty($row[0]))
You could check the number of result rows to see if there are any events:
$result = mysql_query($q);
$numrows = mysql_num_rows ($result);
if($numrows === 0){
...