Can someone please tell me how I can get my $cat_id variable recognised in the SECOND PART of my code ? It works fine in the FIRST PART - I mean the $cat_id value is inserted into mysql database with :
$insert_review_command = "INSERT INTO review VALUES(NULL,'$cat_id','{$category}','$user_id', '{$name}','{$phonenumber}','{$address}', '{$comment}')";
But nothing inserts in the SECOND PART. I don't think my $cat_id is recognised. But why shouldn't it be ?Should $cat_id not be recognised throughout my whole code ? If it is defined within an If statement is it only recognised within that If statement? Thanks for any help.
<?php require('dbConnect.php');
if (isset($_POST['create'])) {
$category = ($_POST['category']);
$name = ($_POST['name']);
$phonenumber = ($_POST['phonenumber']);
$address = ($_POST['address']);
$comment = ($_POST['comment']);
//check if the category being entered is already there
$select_from_cat_table = "SELECT * FROM category WHERE cat_name = '$_POST[category]'";
$result=mysqli_query($con,$select_from_cat_table);
$num_rows = mysqli_num_rows($result);
// get the matching cat_id
$row = mysqli_fetch_assoc($result);
$cat_id = $row["cat_id"];
// ****FIRST PART**** $CAT_ID IS INSERTED INTO THE DB
//if the category name already exists in the category table, then don't add it in again
if($num_rows >= 1) {
echo "This Already Exists<br/>";
//but do add it to the review table
//for the cat_id, we want to get the cat_id of the category name that already exists, that has
//just been posted. This is $cat_id. $user_id is the user id of the person posting
$insert_review_command = "INSERT INTO review VALUES(NULL,'$cat_id','{$category}','$user_id', '{$name}','{$phonenumber}','{$address}', '{$comment}')";
$insert_into_review_table = mysqli_query($con,$insert_review_command);
}
// ****SECOND PART**** $CAT_ID IS NOT INSERTED INTO THE DB
else if ($num_rows < 1)
{
//if it's not in there, then add the category in the category table.
$insert_category_command = "INSERT INTO category VALUES(NULL, '{$category}', '$user_id')";
$insert_into_category_table = mysqli_query($con,$insert_category_command);
//****WHY IS CAT_ID NOT WORKING HERE????******
//and add it to the review table
//for the cat_id, we want to get the cat_id of the category name that already exists, that has
//just been posted. This is $cat_id. $user_id is the user id of the person posting
$insert_review_command = "INSERT INTO review VALUES(NULL,'$cat_id','{$category}','$user_id', '{$name}','{$phonenumber}','{$address}', '{$comment}')";
$insert_into_review_table = mysqli_query($con,$insert_review_command);
echo "Yes, it's been added correctly";
echo $cat_id;
}
$con->close();
header('Location:volleyLogin.php');
}
?>
<!doctype html>
<html>
<body>
<h2>Create new Contact</h2>
<form method="post" action="" name="frmAdd">
<p><input type="text" name = "category" id = "category" placeholder = "category"></p>
<p><input type="text" name = "name" id = "name" placeholder = "name"></p>
<p><input type="text" name = "phonenumber" id = "phonenumber" placeholder = "phone number"></p>
<p><input type="text" name = "address" id = "address" placeholder = "address"></p>
<p><input type="text" name = "comment" id = "comment" placeholder = "comment"></p>
<h2>Visible to :</h2>
<input type="radio" name="allmycontacts" value="All my Contacts">All my Contacts
<input type="radio" name="selectwho" value="Select Who">Select Who
<input type="radio" name="public" value="Public">Public
<input type="radio" name="justme" value="Just me">Just me
<p><input type="submit" name = "create" id = "create" value = "Create new Contact"></p>
Exit
</form>
</body>
</html>
Your logic is split into two parts, if $num_rows is greater than 0, or if it's 0. This is the result of a query, obviously. So when you do
$cat_id = $row["cat_id"];
from the first query, and $num_rows is zero, your $cat_id doesn't hold any values, because mysqli_fetch_assoc() returned no rows (mysqli_num_rows() is 0), so $row is null.
Your solution is to fetch the recent inserted ID from your category table before you insert it into your review table.
Simply add
$cat_id = mysqli_insert_id($con);
before your insert-query for the review table (but after you insert values into the category table).
Related
I have been looking for a solution for this for a while but they all pertain to html tables. I have a simple form and have manually added values into the database using phpMyAdmin. I have a drop down menu at the top and whenever the admin selects a particular name from the drop down menu and presses the 'Display the fields' button, I want all the respective fields to be filled in with the values after which the admin can make changes onto any particular field and update. How can I get those values to be filled? I have tried multiple codes but keep getting errors such as undefined index, undefined variable etc. Can someone help me with that?
<!doctype html>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db_dealer_track";
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("Connection failed". $conn->connect_error);
}
if(isset($_POST['id1'])){
$sql = "SELECT * FROM tbl_dealer_info ";
$sql .= "WHERE $account_name = 'account_name' ";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result)){
?>
<html>
<head>
<title>iMobile </title>
</head>
<body bgcolor = "#D6DFE3">
<center><b><h2>Please enter the following information: </h2></b></center>
<form action = "dealer_track.php" method = "post">
<strong><center> <u>Fields marked with an asterisk(*) are required.</u><br><br>
Name of the dealer:* // This is where the admin selects the user they would like to update
<?php
$sql = "SELECT account_name FROM tbl_dealer_info ";
$result = mysqli_query($conn, $sql);
echo "<select name = 'account_name' id = 'id'>";
echo "<option value = ''>";
while($row = mysqli_fetch_array($result)){
echo "<option value = '" .$row['account_name'] . "'>" . $row['account_name'] . "</option>";
}
echo "</select>";
?>
<br><br>
<input type = submit id = "id1" name = "id1" value = "Display the fields" /><br>
</center>
<hr>
<br><br>
</form>
<form action = "dealer_track.php" method = "post">
Email:*<br>
<input type = "email" name = "email" id = "id3" value = "<?php echo $row['email']?>" Required /><br><br>
RSM:*<br>
<?php
$sql = "SELECT rsm_val FROM tbl_rsm_drop_down ";
$result = mysqli_query($conn, $sql);
echo "<select name = 'rsm_val'>";
echo "<option value = ''></option>";
while($row = mysqli_fetch_array($result)){
echo "<option value = '" .$row['rsm_val'] . "'>" . $row['rsm_val'] . "</option>";
}
echo "</select>";
?>
<br><br>
**// My radio buttons aren't getting checked though**
iPhone Boost Approved:
<input type = "radio" name = "boost_app" <?php if(isset($boost_app)&& $boost_app =="Yes")?> value = "Yes" />Yes
<input type = "radio" name = "boost_app" <?php if(isset($boost_app)&& $boost_app =="No")?> value = "No" />No<br><br>
</form>
<?php
}} // While loop and if loop at the start
?>
</body>
</html>
I'm taking a wild guess here, so I'm assuming you want to select a user from a dropdown (That could be a bad idea if many people are in said database), but you would want to make a simple HTML form and name it somethign you will remember. Under the form put this?
<?php
if(isset($_POST['formnamehere'])) {
$sql = "SELECT * FROM (table name) WHERE accountname=" . $accountname;
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo $row['accountname'];
//put other things here, etc.
}
?>
Granted this code is not meant to be used exactly. but to give you a general idea.
You code is a bit messy but here is what you need to do generally.
First query for the unique record:
$sqlQuery = "SELECT id, firstname, lastname FROM Table Where id = '$id'";
Then run the query:
$result = $connection->query($sqlQuery ); //nb: $connection is your connection variable
Then check if any result found:
if ($result->num_rows > 0) { ........ }
If any records found then put the fetched data in variables like this
while($row = $result->fetch_assoc()) {
$firstname = $row["firstname"];
$lastname = $row["lastname"];
//and so on....
}
// You can display these variables any how you want in here, eg:
echo "<h2>$firstname</h2>";
or
<input type="text" id="firstname" name="firstname" value="<?php echo $firstname ?>" />
//nb: you must close the php tag before using html and re open it after
if "if ($result->num_rows > 0) {...} is false, just use an else {...} to display a message
You can run a query with your active connection to fetch your respective information from the table you want, along with a search clause for where the name is equal to a given value.
Query:
$result = mysqli_query($con, "SELECT `data` FROM `table` WHERE `name` = '$name';");
You can then display your data on your front end by outputting the result.
<?php
if($row = mysqli_fetch_array($result)) {
echo $row["data"];
}
?>
Working my way though Creating, Reading, Updating & Deleting (CRUD) information from a database I have done C,R & D but for some reason I can not update.
What am trying to do:
Edit a categorizes title
My Results:
when clicking edit in the table of the cat title I want to change I can get the cat title to echo into a form, where it can be changed then when i try and change the cat title, click update the form goes away as I wanted but the cat title stays the same.
as well am not getting any query errors
What should I look for when debugging code that has no errors?
Can someone see my problem?
if (isset($_GET['edit'])) {
$cat_id = $_GET['edit'];
include "includes/update.php";
}
?>
<form action="categories.php" method="post">
<div class="form-group">
<label for="cat_title">Edit Category</label>
<?php
if (isset($_GET['edit'])) {
$cat_id = $_GET['edit'];
$query = "SELECT * FROM categories WHERE cat_id = $cat_id ";
$select_categories_id = mysqli_query($connection,$query);
while ($row = mysqli_fetch_assoc($select_categories_id)) {
$cat_id = $row['cat_id'];
$cat_title = $row['cat_title'];
?>
<input value="<?php if(isset($cat_title)){echo $cat_title;} ?>" class="form-control" type="text" name="cat_title">
<?php
}
}
if(isset($_POST['edit_category'])){
$edit_cat_title = $_POST['cat_title'];
$query = "UPDATE FROM categories SET cat_title = '{$edit_cat_title}' WHERE cat_id = {$cat_id} ";
$edit_query = mysqli_query($connection,$query);
if (!$edit_query) {
die(mysqli_error($edit_query));
}
}
?>
</div>
<input class="btn btn-primary" type="submit" name="edit_category" value="Edit Category">
</form>
In the following line you have a small error:
$query = "UPDATE FROM categories SET cat_title = '{$edit_cat_title}' WHERE cat_id = {$cat_id} ";
You need to remove the "FROM" in there, will look like this:
$query = "UPDATE categories SET cat_title = '{$edit_cat_title}' WHERE cat_id = {$cat_id} ";
and it should work as expected.
you're calling the update query with
$query = "UPDATE FROM categories SET cat_title = '{$edit_cat_title}' WHERE cat_id = {$cat_id} ";
where $cat_id probably is not set,
once to get this value you're using an if condition
if (isset($_GET['edit'])) {
$cat_id = $_GET['edit'];
where the $_GET[ 'edit' ] can be empty, and the next error is to overwrite the $cat_id variable in a loop: $cat_id = $row['cat_id'];
if (isset($_GET['edit'])) {
$cat_id = $_GET['edit'];
include "includes/update.php";
}
?>
<form action="categories.php" method="post">
<div class="form-group">
<label for="cat_title">Edit Category</label>
<?php
if (isset($_GET['edit'])) {
$cat_id = $_GET['edit'];
}
if(isset($_POST['edit_category'])){
$edit_cat_title = $_POST['cat_title'];
$query = "UPDATE FROM categories SET cat_title = '{$edit_cat_title}' WHERE cat_id = {$cat_id} ";
$edit_query = mysqli_query($connection,$query);
if (!$edit_query) {
die(mysqli_error($edit_query));
}
}
Delete that FROM, it should be UPDATE categories SET ...
You realise that $edit_cat_title is from a POST value, but $cat_id is from a GET value, but your form (as far as I can see) has an action value of action = "categories.php" which will contain NO GET VARIABLES.
Add the property enctype to your <form> such as:
<form ... enctype='multipart/form-data' ... >
To be honest this last point is good practise but I'd be surprised if that was why your POST data was not being populated.
Possible solutions:
1) Use $_REQUEST['cat_id'] and insert the cat_id as a POSTed field in your form, so it can use variables given by either $_POST or $_GET [or $_COOKIE].
2) change your action to goto : action ="categories.php?edit=XXX" to submit the form to an address with a valid GET value as required.
3) Use sessions to hold data from previous pages (such as cat_id). This is my prefered option.
Extra
From question comments it becomes clear that the part if isset($_POST['edit_category']) is never true, so this means that your form is incorrect -- either you have not got a form field named name='edit_cateogry' or your form field is never filled in, or never sent with the form (perhaps the input is placed after the </form> form closing tag?
Anyhow, your issue is that your $_POST value you are looking for is never set.
This code is meant to check the submitted form values and update the table,
however it just replaces the field with a blank
Any ideas where it is gone wrong, please?
<form action = "update.php" method = "POST">
<p>
New Name: <input type "text" name="name">
<input type= "submit">
</p>
</form>
<?php
require ('/var/www/html/site1/connect_db.php');
if(!empty($_POST['name']) && !is_numeric($_POST['name']))
{
$name=$_POST['name'];
$name=mysqli_real_escape_string($dbc,$query);
$name=strip_tags($name);
#$query='update customers SET customerName = '".$name."' where customerNumber=114';
$query = "update customers ". "SET customerName = $name"."where customerNumber=114" ;
mysqli_query($dbc,$query);
}
else
{
echo $name;
}
$query = 'select * from customers where customerNumber=103';
$result = mysqli_query($dbc,$query);
while ($row=mysqli_fetch_array($result, MYSQLI_NUM))
{
echo"<p>Name : $row[1]</p>";
}
mysqli_close($dbc);
?>
You are updating customer number 114 but selecting 103 out, whose name may be blank.
Your update statement needs to have quotes around the $name bit as below:
$query = "UPDATE customers SET customerName = '$name' WHERE customerNumber=114";
Edit: please see the parameterised query advice in the question comments.
i have multiple checkbox values in my form as shown in figure
I know i can store values for single checkbox in db but here situation is slightly different,so ho could i successfully store them in different different rows for same db.
my table struture is
1.content_table
title,description,category_id(fk),course_id(fk),subject_id(fk),content_type_id(fk)
2.category_table
entrance,school,ug,pg
3.subject_table
english,hindi,maths......
4.content_type_table
notes,summary,videos,question_bank
i have to insert data from shown form in content_table which store data by category_id,course_id,subject_id,content_type_id
i have tried following code which is only working for single checkbox i.e category ,so please someone suggest me how to do for different type of checkbox.
my code is
<?php
include 'includes/dbconfig.php';
if($_SERVER['REQUEST_METHOD']=='GET')
{
echo $title = $_GET['title'];
echo $description = $_GET['description'];
echo $content_url = $_GET['content_url'];
echo $thumb_icon_url = $_GET['thumb_icon_url'];
$category = $_GET['category'];
$course = $_GET['course'];
echo $select_subject = $_GET['select_subject'];
echo $select_content_type = $_GET['select_content_type'];
foreach (array_combine($category, $course) as $cat => $cose) {
$sql = mysqli_query($conn,"SELECT category_id from category_ref_table where category = '$cat'") or die(mysqli_error());
$row = mysqli_fetch_array($sql,MYSQLI_ASSOC);
echo $category_id = $row['category_id'];
$sql1 = mysqli_query($conn,"SELECT course_id from course_ref_table where course = '$cose'") or die(mysqli_error());
$row1 = mysqli_fetch_array($sql1,MYSQLI_ASSOC);
echo $course_id = $row1['course_id'];
$sql2 = mysqli_query($conn,"SELECT subject_id from subject_ref_table where subject = '$select_subject'") or die(mysqli_error());
$row2 = mysqli_fetch_array($sql2,MYSQLI_ASSOC);
echo $subject_id = $row2['subject_id'];
$sql3 = mysqli_query($conn,"SELECT content_type_id from content_type_table where content_type = '$select_content_type'") or die(mysqli_error());
$row3 = mysqli_fetch_array($sql3,MYSQLI_ASSOC);
echo $content_type_id = $row3['content_type_id'];
mysqli_query($conn,"INSERT INTO content_ref_table (title,description,content_url,thumb_icon_url,category_id,course_id,subject_id,content_type_id,login_id)VALUES ('$title','$description','$content_url','$thumb_icon_url','$category_id','$course_id','$subject_id','content_type_id')");
}
}
?>
try something like this(array variable)
<input type="checkbox" name="category[]" value="entrance">
<input type="checkbox" name="category[]" value="School">
<input type="checkbox" name="category[]" value="ug">
<input type="checkbox" name="category[]" value="pg">
Upon using like this you can get the list of checked items as an array. After that do the required save it in your table.
I've a problem when updating multiple Mysql rows when using an array, Lets start with the following submit form :
$n = array(); //Supplier Name
$s = array(); //Short Name
$o = array(); //Shipment No.
$id = array(); //Supplier ID
<form action="editing_supplier.php" method="post">
<input type="hidden" value="<?php echo $row['id'] ?>" name="id[]">
<input type="text" value="<?php echo $row['name']?>" required name="n[]">
<input type="text" value="<?php echo $row['short_name']?>" required name="s[]">
<input type="text" value="<?php echo $row['shipment_no']?>" required name="o[]">
<input type="submit" value="Confirm Editing" >
</form>
Now when clicking Submit, which directly opens up "editing_supplier.php" page- The following codes are bellow :
if((isset($_POST['n'])) && (isset($_POST['s'])) && (isset($_POST['o']))){
//Shows up the ID for each Supplier Name
if(is_array($_POST['id'])) {
foreach($_POST['id'] as $id){
//Updates Supplier Name
if(is_array($_POST['n'])) {
foreach($_POST['n'] as $value){
$query = "UPDATE suppliers SET name = '".$value."' where id ='".$id."'";
$result = mysql_query($query);
}
}
//Updates Short_Name
if(is_array($_POST['s'])) {
foreach($_POST['s'] as $value1){
$query = "UPDATE suppliers SET short_name = '".$value1."' where id ='".$id."'";
$result = mysql_query($query);
}
}
//Updates Shipment No.
if(is_array($_POST['o'])) {
foreach($_POST['o'] as $value2){
$query = "UPDATE suppliers SET shipment_no = '".$value2."' where id ='".$id."'";
$result = mysql_query($query);
}
}
//End of for Each id
}
}
What actually Does, When Selecting a single row to update..It works perfectly ! But when doing a multiple selection in-order to make an update for them, it messes up all the values..As if copying the last id,supplier name, short name and shipment no. to all the selected rows.
I think this is due to the series of foreach within the foreach($id). I would write :
foreach($_POST['id'] as $index=>$id) {
to keep track of the index of your record, and then do not do any other foreach but rather :
$query = "UPDATE suppliers SET name = '".$_POST['n'][$index]."' where id ='".$id."'";
so you keep the link between the $id value and the other variables.