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.
?>
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 am trying to make value +1 in database every time use use button.
my function in HTML:
function onClick(arg){
alert("thx fo click");
$.ajax({
type: 'POST',
url: 'data.php',
data: {
'arg': arg,
},
success: function(response) {
}
});
}
arg means value of button and it is a ID for a row in the database
and PHP:
<?php
$link = mysql_connect($servername, $username, $password);
$id = $_POST['arg'];
$sql = "UPDATE Buttons(SUMA) SET SUMA = SUMA + 1 WHERE ID = '$id'";
$conn->query($sql);
mysql_close($link);
?>
And that make nothing. How can i fix it?
You have several syntax errors here.
First and foremost though, check out mysqli_ (or PDO) and start using that instead of mysql_
For why to use mysqli_ - MySQL vs MySQLi when using PHP
Comparing mysqli_ and PDO - https://websitebeaver.com/php-pdo-vs-mysqli
With that out of the way....
You're defining your database connection without selecting a schema, but don't reference your schema in the query, meaning mysql won't know what to update. Either reference your schema in the connection or in each query. Also check on your table name, is it really Buttons(SUMA)?
You defined your database connection as $link, but are using $conn to attempt the query. Probably a 'typo' from copy and paste. Be careful of this...
As Artistic Phoenix mentioned, you have to make sure you're column cannot be set to NULL, and starts at 0 to begin. While you're at it and we're going through, make sure your datatype is set to int for the increment count.
After making those changes if you don't have success, I'd try running your query outside your code in a DB manager to ensure that portion is having the intended affect on your data, before looking at the errors in your code.
I'm guessing the arugment is passing correctly to your script, but to confirm, you can always echo it on the backend, and to be doubly sure alert() it in JS before it's passed through.
Take the time to go through that reading, update your script to use mysqli_ or PDO, and if you're still having troubles, I'm more than happy to jump back in here and help you further.
What is 1 + NULL it's still NULL.
IF you didn't default the column to '0' , then you can't increment it.
This can best be shown in a simple DB fiddle
Starting Null:
CREATE TABLE t(
id INT(10),
v INT(10)
);
INSERT INTO t (id)VALUES(1);
SELECT * FROM t;
UPDATE t SET v = v+1 WHERE id=1;
SELECT * FROM t;
In Both selects you will get a value of null for v as seen below in the fiddle:
https://www.db-fiddle.com/f/m1vgKpov1oiRJEfZEgmk1j/0
In simple terms, you cannot add 1 (or any number) to a NULL value. Well you can but it's still null. null + 1 = null
Starting 0:
CREATE TABLE t(
id INT(10),
v INT(10) default 0
);
INSERT INTO t (id)VALUES(1);
SELECT * FROM t;
UPDATE t SET v = v+1 WHERE id=1;
SELECT * FROM t;
In this case the first Select return 0 for v and the second returns 1 for v. As seen in the modified fiddle.
https://www.db-fiddle.com/f/m1vgKpov1oiRJEfZEgmk1j/1
Also (SQLInjection)
As I said in the comments:
What if arg = "' OR 1 --"
Or in other words don't inject user variables (or any clientside data) into your SQL or it winds up looking like this:
UPDATE `Buttons(SUMA)` SET SUMA = SUMA + 1 WHERE ID = '' OR 1 --'"
Which will increment every row in your DB that is not null. Basically the ' closes the other quote, then OR 1 is always true(for every row). Unfortinalty I cant show the -- comment part in the fiddle (it comments out the second select), but here is the end result.
https://www.db-fiddle.com/f/m1vgKpov1oiRJEfZEgmk1j/3
This is why we use prepared statements. This example is somewhat trivial but I have seen login code on here I was able to bypass simple by putting "' OR 1 LIMIT 1 --'" in, and with offset you could iterate though each user. They were looking for 1 row to be returned on the match of a username and password.
A few other things:
Table name Buttons(SUMA) is that really the name, as it will only work if escaped with the backtic. As I did in the above SQLInjection example.
$link = mysql_connect($servername, $username, $password); are these defined, the open tag is right above them. I generally chock that up to simplified example code. But it's worth asking. Obviously you can't connect to the DB if those are undefined.
Cheers!
I need a query to execute when entering a page (php). I've already added this to the top.
Code:-
mysql_query("INSERT INTO `table_name` (`player_id`, `unit1`, `unit2`, `unit3`, `unit4`)
VALUES ('".$_SESSION['user']['id']."', 0, 0, 0, 0)");
When my users enter the page that contains that, the query should be executed. Yes database connection is included.
How do I fix this? (also will it duplicate player_id)?
First mysql is deprecated use mysqli.
Your query is fine how i can see, but your table could be a problem.
You should not have primary key on player_id if you wish to duplicate player_id. (Otherwise keep the primary key).
Also if you wish to have one player_id with those results (not multiple / duplicates), then you could create query in this way:
$query = "INSERT INTO `table_name` (`player_id`, `unit1`, `unit2`, `unit3`, `unit4`)
VALUES ('".$_SESSION['user']['id']."', 0, 0, 0, 0)
ON DUPLICATE KEY UPDATE `unit1`=0, `unit2`=0, `unit3`=0, `unit4`=0";
UPDATE:
Also there could be a problem that you are missing a database identifier at mysql_query:
mixed mysql_query ( string $query [, resource $link_identifier = NULL ] )
like mysql_query("MYQUERY", $mylinkISavedAtConnectingToDatabase);
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;.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
My question: I have a php search form in which I need the user to be able to redefine the search for only a part of the string.
Example (so far the user enter):
// Search Option
name: 20081111-1 //which means that the date of the item is 2008-11-11
Now, I would like the user to make a search which it will only include all the items in 2008 (desired user search):
// Search Option
name: 2008*
How can I make this option in my search? Then I can search in my database for this part of the string only.
Thanks!
Javascript:
var str = '200811111-1';
var hasSubString = str.indexOf('2008') > -1;
var startsWithString = str.indexOf('2008') == 0;
MySql:
Has Substring 2008:
select * from table where col like '%2008%'
Starts with 2008:
select * from table where col like '2008%'
Option 1:
You would take the PHP variable and replace the asterisk (*) with a percentage sign (%):
<?php
$name = $_POST['name']; // remember to sanitize it
$name = str_replace('*', '%', $name);
?>
You would then create a MySQL query using your variable:
$query = "SELECT * FROM table WHERE column LIKE '$name'";
Option 2:
Use a MySQL date query:
$query = "SELECT * FROM table WHERE YEAR(column) = '2008'";
Note that column should be a date or a datetime type.
You should add contextual help for users or even dropdowns with possible options, so they don't search for '20081', for example.
In this specific case you can use in your query
date like '%2008-%'
instead of
date = '2008-11-11'
that means search for rows where date field contains the following pattern "2008-".
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;
With this in sql you search using a pattern in your case 2008, you can use regular expression for do dynamically searching only numbers that start by 2.