This is my category table. Basically there's a category and subcategory. The ParentCategoryId is the subcategory under the category. For example I have three of ParentCategoryID 1 which means it's a subcategory under category_id 1 therefore the isSubCategory is set to 1 that is saying yes it's a subcategory and 0 means it's a category that's why the parentCateogryID is null for the first four data since they are categories
I already have an Add Category functioning and now I want to have an Add Subcategory function but very confused on how I will do my usual php query.
<form method="POST">
<?php
if(isset($_POST['submit'])){
include 'testdb.php';
$addcategory = $_POST['categoryname'];
$parentcategory = $_POST['parentcategoryID'];
$query = mysqli_query($con, "SELECT categoryname FROM category WHERE categoryname = '.$addcategory.'");
$insert = mysqli_query($con, "INSERT INTO category (`categoryname`,`ParentCategoryID`,`isSubCategory`) VALUES ('$addcategory','$parentcategory','1')");
if(!$insert){
echo mysqli_error($con);
}
else{
echo 'Category successfully added!';
}
}
?>
structure
whenever im trying to add.
needs to have the same id as(look pic below)
this needs to be the same so the inserted sub category shows in Foods category table
Foreign keys aren't self-referential within the same table. If your subcategories were in a different table (which I'd recommend - the above solution is really messy), then a foreign key would make it much easier for your insert functions.
Anyway, if you just wanted to add a new subcategory;
$addcategory = $_POST['categoryname'];
$parentcategory = $_POST['parentcategory'];
$insert = mysqli_query($con,
"INSERT INTO category
(`categoryname`,
`ParentCategoryID`,
`isSubCategory`)
VALUES
('$addcategory',
'$parentcategory'
'1')");
Also, consider using prepared statements.. or at least run mysqli_escape_string over the POST params you're taking in.. leaving them as they are would allow me to insert a category like '; DROP TABLE users;.
Related
I'm inserting some values to a table using a sql statement. All the values get inserted, except the 'qty' column. When I do an echo for sql statement, it shows the value has been assigned to the sql statement. Table column data type is INT. Can anyone help me to spot the problem?
$it_code = $_POST['id'];
//Prompt user to enter required qty
echo '<script>';
echo 'var qty = prompt("Enter Qty", "");';
echo '</script>';
//Get the item details from item table
$sqlString = "Select * from items where it_code='".$it_code."'";
$objItem = new Allfunctions;
$result = $objItem->retriveData($sqlString);
//Get the selected qty from java script to php variable
$qty = "<script>document.writeln(qty);</script>";
$user_id =$_SESSION['user_id'];
//Insert to orders table
$sqlStringInsert = "INSERT INTO orders(user_id,it_code,qty,status,tr_timestamp) VALUES ('$user_id','$it_code','$qty','PENDING',CURRENT_TIMESTAMP())";
echo $sqlStringInsert;
$objItem->addToTable($sqlStringInsert,'Succsessfully added.','Error adding'); // This is a custom built method to insert data in to a table by taking the sql statement as the parameter
Following is the sql statement generated,
Following is the table data. Qty is always 0 eventhood the sql statement had a value at qty column.
Obligatory warning
The code as you have shown it should not be used in production as it is vulnerable to SQL-injection attacks. Preventing this is well covered on this site in other answers.
Answer
The issue is that the value of $qty you are injecting into your SQL is the string "<script>document.writeln(qty);</script>". You just can't see it because you are likely echoing it out to the browser to test it.
Wrap your echoing of the SQL statement in a call to htmlentities() (docs) to see what's actually happening.
Depending on the version and settings, MySQL is very forgiving of bad data being injected to a column. In this case, it sees a string of text being inserted to a numeric column, and just truncates it to 0. See this in action here:
CREATE TABLE Foo (
Id INT,
Qty INT
);
INSERT INTO Foo(Id, Qty) VALUES (1, 'a string of text');
SELECT * FROM Foo; -- returns a row (1, 0)
https://www.db-fiddle.com/f/dEoaYGEyXEjs6ocVBwyyyr/1
I have made a gravityform risk assessment quiz. Depending on answers, assigns respondent a profile: aggressive, balanced, conservative. I have 3 MySQL tables with names corresponding to each of those profiles.
This is a single query for 1 of the 3 tables:
$query= "
SELECT value1
, value3
, value4
FROM aggressive
order
by num
LIMIT 7,8
";
This is the gravityform field showing “aggressive, balanced or conservative”:
$profile = slideval($_POST["input_31"]);
How do I write the MySQL query so it selects the right profile and display result in 1 single HTML page, instead of having to create 3 different HTML pages with 3 different queries?
Thanks a lot!
$profile = slideval($_POST["input_31"]);
$query= "SELECT value1,value3,value4 FROM $profile order by num LIMIT 7,8";
You can go with union or unionall
$query = “
SELECT value1,value3,value4 , ‘aggressive’ As tablename FROM aggressive
UNION
SELECT value1,value3,value4 , ‘aggressive’ As tablename FROM balanced
UNION
SELECT value1,value3,value4 , ‘aggressive’ As tablename FROM conservative”;
$ResultLine = $db->query("SELECT customerid FROM mydb WHERE surname= Holmes ORDER BY customerid DESC LIMIT 10")->fetchArray();
$res = $ResultLine[0];
echo json_encode($res);
Let's say there are 3 customers with the same surname in the database and different customerid. How can I structure the code above to return all the pairs customerid/surname as an array to my html page? The code above obviously only returns one customerid.
The call to fetchArray() returns one row at a time. So this snippet gets the first row and sends the first element ([0]) to json_encode. Remove ->fetchArray() from the set statement, then iterate over $ResultLine, something like:
while ($row = $ResultLine->fetchArray()) {
//do something with $row values
}
Doc found here
I am creating an Inline Edit data by using X-editable with PHP Dropdown Select Box. I am facing an issue in that I am not able to create a dynamic select option in jquery from database data.
Actually, I want to echo the source format of text in PHP so I can add in jquery. The snippet below is in the correct format, but I don't know how to echo that text dynamically using data from PHP.
-- PHP --
$stmt = $connect->prepare("SELECT * FROM `profile`");
$stmt->execute();
-- JQUERY --
$('#employee_data').editable({
container: 'body',
selector: 'td.gender',
title: 'Gender', dataType: 'json',
source: [{value: "Male", text: "Male"}, {value: "Female", text: "Female"}]
});
Please help me to create this json structure [{value: "Male", text: "Male"}, {value: "Female", text: "Female"}] from a server-side query and pass it into the editable() function's argument in jquery.
I tried this, but it didn't work:
$result = $stmt->fetchAll();
foreach($result as $data => $value) {
$data = array('value' => $value["category_id"], 'text' => $value["category"]);
}
$category_list = json_encode($data);
There is a simple logic error here - you are overwriting the value of $data every time your loop runs, so you'll only ever end up encoding the value of whatever the last entry in your data was.
Instead you need to declare an array, and then add items to that array each time you loop:
$result = $stmt->fetchAll();
$list = array();
foreach($result as $data => $value) {
$list[] = array('value' => $value["category_id"], 'text' => $value["category"]);
}
$category_list = json_encode($list);
And then in the JavaScript, simply write:
source: <?php echo $category_list; ?>
There are several points to inform you of...
If you are not using any placeholders in your sql, then using a prepared statement is needless overhead. Just use query().
Do not ask for more data from your SELECT clause than you actually intend to use. I don't know how many columns are in your table, but you only need to be fetching category_id and category according to your posted script.
By aliasing your column names in your SELECT clause, you can avoid the extra step of iterating the result set's rows just to adjust the keys.
There seems to be a disconnect in your post between category_id & category versus gender & gender. I don't know exactly what data is being used to create these <option>s, but I would like to tell you that there is never any benefit to repeating identical text in the option's text and the same option's value attribute. In other words, <option value="Male">Male</option> should only ever be written as <option>Male</option>; the former is simply redundant markup bloat. I will assume that category_id and category are not identical values, so there should be no concern for redundancy.
fetchAll() is most appropriately used when you are not iterating the data in the same "layer". Because the server-side (php) data is being passed to the client-side (js), there is no need to manually iterate the result set to create an array; just let fetchAll() do all of the work.
Code: (assuming you are querying in the same file that you are printing to screen)
source = <?php echo json_encode($pdo->query("SELECT `category_id` AS `value`, `category` AS `text` FROM `profile`")->fetchAll()); ?>
There is a bounty of good advice/techniques # https://phpdelusions.net/pdo_examples/select
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am trying to update a table row using the below code
t.executeSql('UPDATE flatcomments SET BuildingCode = ?, FlatNo = ?, Comment = ?, Closed = ?, New = ?)',
[buildingcode, flatdescription, flatcomment.toUpperCase(), 1, 1]);
with no success. Where am i wrong
This is a nice PHP tutorial.
All SQLite commands will work for you.
<?php
# CREATING A TABLE
$dbname = 'base';
$mytable ="tablename";
$base= new SQLiteDatabase($dbname, 0666, $err);
if ($err) exit($err);
$query = "CREATE TABLE $mytable(
ID bigint(20) NOT NULL PRIMARY KEY,
post_author bigint(20) NOT NULL,
post_date datetime,
post_content longtext,
post_title text,
guid VARCHAR(255)
)";
$results = $base->queryexec($query);
# The SQL command CREATE TABLE defines the columns. It is sent to the SQLite manager by the PHP method queryExec() which returns true or false, depending on whether the operation is successful or not.
# See the code of the script sqlite-create-table.php.
# ADDING POSTS
# The table of posts that we just created will be filled, like in Wordpress, with the posts we write, each post corresponding to a row of the table.
# The SQL command: INSERT INTO allows to store the data.
$number = 1;
$title="My first post";
$content="The content of my post...";
$date = strftime( "%b %d %Y %H:%M", time());
$author=1;
$url = "http://www.lantian.eu";
$query = "INSERT INTO $mytable(ID, post_title, post_content, post_author, post_date, guid)
VALUES ('$number', '$title', '$content', '$author', '$date', '$url')";
$results = $base->queryexec($query);
# For the purposes of the tutorial, we place the contents of the post directly into variables. In practice these variables will be assigned from an t online or local ext editor, as shown in the CMS tutorial.
# The author is represented by the number 1 because Wordpress does not put the names in the posts table but in a separate table instead.
# The guid column contains the URL of the post that also serves as an ID unique.
# The INSERT command jas for first parameter the table name and in parentheses the list of columns to fill, then the parameter VALUE provides a list of values corresponding to the columns in the same order.
# Thus, post_title, which contains the titles, will has for value $title, the variable that was assigned the title of the post.
# The same queryExec method is used to send the request.
# Source code of the script sqlite-write.php.
# READING A POST
# You can access the contents of the database with the SELECT command.
$query = "SELECT post_title, post_content, post_author, post_date, guid FROM $mytable";
$results = $base->arrayQuery($query, SQLITE_ASSOC);
$arr = $results[0];
if($results)
{
$title = $arr['post_title'];
$content = $arr['post_content'];
$user = $arr['post_author'];
$date = $arr['post_date'];
$url = $arr['guid'];
}
# To the SELECT command is given the list of columns that you want get the content and lines will be assigned to $results array. Indeed, the arrayQuery PHP method returns an array of arrays, each representing a line of the table.
# In practice we will use instead other commands that we will see later to limit the resources usage.
# Data are retrieved in the associative array $arr, where the column names are keys and their content the values.
# Source code of the script sqlite-read.php.
# DELETING A TABLE
# The deletion of a table is made by the DROP TABLE command of SQL.
$query = "DROP TABLE $mytable";
$results = $base->queryexec($query);
# See the code sqlite-delete-table.php.
?>