php generate a string and check from mysql with not exist - php

I want to generate a string to post a url. Then make the post url like: http://www.mydomain.com/post/afCeYk, and store this url in the mysql. In order to avoid a repeat url , I think first should check the mysql whether the url has already existed. In my code, I just check once, I can not ensure the second generate string hasn't already existed. So how do I make a loop?
$shufstr = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$rdstr = substr(str_shuffle($shufstr),0,6);
$query = mysql_query("select * from table where post_url = '".$rdstr."'");
if(mysql_num_rows($query)>0){
//insert the url rules into db
}else{
//generate a new string and check the db again
}

You should query the database once to collect all of the data from the table, then generate a string and check it against the array you get.
As opposed to querying the database over and over, this has a performance benefit.
(not actual code)
$url_list = query("SELECT `post_url` FROM `table`");
do {
$random_string = generate_random_string();
}
while(!in_array($random_string, $url_list));
In addition, make sure no duplicate is entered by making the column UNIQUE.

You can use a while loop, but it would get pretty slow after you have a few thousand URLs saved:
$shufstr = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$validString=false;
while(!$validString){
$rdstr = substr(str_shuffle($shufstr),0,6);
$query = mysql_query("select * from table where post_url = '".$rdstr."'");
if(mysql_num_rows($query)==0){ //This is also different from your code as you don't want to do the insert if there is 1+ row with that url.
$validString=true;
//insert the url rules into db
}
}

If it were my project, I would add a UNIQUE constraint on the post_url column itself, this will ensure that no duplicates will be entered from any point of entry (app, command line, etc). More info on MySQL unique.

Related

php files on the fly

In PHP, If i have this assign:
$link = 'Home';
And in another php section i need to grab the value of $link and insert it in a MYSQL query in plain text, like this:
$sql = "SELECT txt FROM Home WHERE id = 1";
Note that $link has been written in the format of it's value in the query.
Basically i need to see the inside of the $link var and write it down on the query.
Why i need this -> because i'm creating php files on the fly after the click of a submit button.
And inside of the newly created file is a tinymce text editor that needs to read it's text contents from a table that was also created on the fly along with this file.
What you want to do is this:
$sql = "SELECT txt FROM $link WHERE id = 1";
^ ^ ^
The double-quotes (") specify that the string has to be interpreted (with single quotes this won't work). Inside the string you can then write the name of the variable ($link) and it will be "supplanted" by its value.
I would'nt recommend doing this because it is vulnerable to SQL-injection and it is a very very bad practice that show that you do things in an uncommon way. Better avoid it!
EDIT: even worse...
When you say in a comment creates a mysql table with the name of the file that's an even worse thing to do. First, not all characters in a filename should go into a table name. Second, you can get litearlly anything as a filename, even things that are not actual filenames.
It is possible to forge a HTTP request so that the filename is an arbitrary string of your liking, for example:
a (); SELECT * FROM accounts; --
When you put this string into your query:
CREATE TABLE $filename (id int PRIMARY KEY, whatever varchar(20) NOT NULL);
You get this resulting SQL query:
CREATE TABLE a (); SELECT * FROM accounts; -- (id int PRIMARY KEY, whatever varchar(20) NOT NULL);
As you can see, this will create a table a without any columns and then select all usernames and passwords, if the table accounts exists. The rest of the query is commented out with --.
This is a very simple SQL injection attack and you don't want to do this! Don't put userinput straight up into your SQL queries!!
EDIT: taking the value from $_POST
If your field has the name link then you can access it with
$_POST['link']
You can put this into your string this way:
$sql = "SELECT txt FROM {$_POST['link']} WHERE id = 1";
Do you want something like this:
$sql = "SELECT txt FROM ".$link." WHERE id = 1";

SQL - change an existing row

I'm using PHP in order to create a website where managers have access and review forms that employees have submitted. In the reviewing PHP file, I have created two buttons which basically approve or disapprove the form. After they click on one of the buttons, they are being redirected to another PHP file which actually inserts into the MySQL Database a change in a column I named 'processed'. It changes 0 which is unprocessed to 1, which is processed. The table I am referring to has columns such as formid, fullname, department and other job related stuff, as well as the 'processed' column which allows the managers to see if there is a pending form to be reviewed.
My problem is that I have no idea how to actually allow MySQL to find the proper row and change only the cell with the name 'processed' from 0 to 1 without having to insert every cell again. Here's what I have tried till now:
$id = $_SESSION[id];
$fullname = $_SESSION[fullname];
$teamformid = $_SESSION[teamformid];
if (isset($_POST['approved'])) {
$sql = "INSERT INTO carforms (processed) where aboveid='$id' and processed='0' and teamformid=$teamformid
VALUES ('0')";
}
else if (isset($_POST['disapproved'])) {
//todo
}
How do I tell SQL to only find the specific row I want and change only one column which is processed?
Also, do I always have to type every column name when I use the INSERT INTO command?
Thanks in advance.
Use the Below code it'll work for you.
$id = $_SESSION[id];
$fullname = $_SESSION[fullname];
$teamformid = $_SESSION[teamformid];
if (isset($_POST['approved'])) {
$sql = "UPDATE `carforms` SET processed = '1' WHERE `aboveid` = '".$id."' AND `teamformid` = '".$teamformid."'";
}
Try:
"UPDATE carforms SET processed = 1 WHERE aboveid = $id AND teamformid = $teamformid"
From what I have interpreted from your question, it seems like you need to use the MySQL UPDATE command. This will update any existing rows.
For example, let's say you have a table called 'forms', consisting of a Primary Key 'form_id' and a field named 'processed'.
If we want to change the value of 'processed' to '1', we would run...
UPDATE forms SET processed = 1 WHERE form_id = [whatever number the form is];
Obviously this only works where the form (with a form_id) exists already
There is no "INSERT...WHERE" in SQL.
To change an existing record there are 2 options, REPLACE or UPDATE. The former will create the record if it does not already exist and has similar syntax to INSERT. UPDATE uses the WHERE clause to identify the record(s) to be changed.
Using REPLACE is tricky. It needs to work out whether it should INSERT a new record or UPDATE an existing one - it does this by checking if the data values presented already exist in a unique index on the table - if you don't have any unique indexes then it will never update a record. Even if you have unique indexes just now, the structure of these may change over time as your application evolves, hence I would recommend NOT using REPLACE for OLTP.
In your question you write:
where aboveid='$id' and processed='0' and teamformid=$teamformid
(it would have been helpful if you had published the relevant part of the schema)
'id' usually describes a unique identifier. So there shouldn't be multiple records with the same id, and therefore the remainder of the WHERE clause is redundant (but does provide an avenue for SQL injection - not a good thing).
If the relevant record in carforms is uniquely identifed by a value for 'id' then your code should be something like:
$id=(integer)$id;
$sql = "UPDATE carforms SET processed = $action WHERE aboveid=$id";
But there's another problem here. There are 3 possible states for a record:
not yet processed
declined
approved
But you've only told us about 2 possible states. Assuming the initial state is null, then the code should be:
$action=0;
if (isset($_POST['approved'])) {
$action=1;
}
$id=(integer)$id;
$sql = "UPDATE carforms SET processed = $action WHERE aboveid=$id";
if ($id &&
(isset($_POST['disapproved']) || isset($_POST['approved']))
) {
// apply the SQL to the database
} else {
// handle the unexpected outcome.
}

MySQL error: Incorrect Table Name

I'm pretty new to web development so there's a good chance I'm doing something pretty dumb here.
I'm using AJAX to send data to a PHP file which will use the data to run SQL commands to update a table. I'm dealing with editing articles, so my PHP file needs to know three things: The original name of the article (for reference), the new name and the new content. I also tell it what page the user is looking at so it knows which table to edit.
$('#save_articles').click(function () {
var current_page = $('#current_location').html();
var array_details = {};
array_details['__current_page__'] = current_page;
$('#article_items .article_title').each(function(){
var article_name = $(this).html(); //The text in this div is the element name
var new_article_name = $(this).next('.article_content');
new_article_name = $(new_article_name).children('.article_content_title').html();
var new_article_content = $(this).next('.article_content');
new_article_content = $(new_article_content).children('.article_content_content').html();
array_new_deets = {new_name:new_article_name, content:new_article_content};
array_details[article_name] = array_new_deets;
});
send_ajax("includes/admin/admin_save_articles.php", array_details);
});
In the PHP file, I first retrieve the current page and store it in $sql_table and then remove the current page variable from $_POST. Then I run this.
foreach($_POST as $key => $value){
$original_name = $key;
$new_name = $value['new_name'];
$new_cont = $value['content'];
$query = "UPDATE
`$sql_table`
SET
`element_name`= '$new_name',
`element_content` = '$new_cont',
WHERE
`element_name` = '$original_name'";
$query = mysql_query($query);
if(!$query){
die(mysql_error());
}
}
I always receive an error saying that 'sitep_Home' is an incorrect table name. Not only is it a real table in my db, but I've actually changed its name to make sure it isn't an issue with keywords or something.
If I instead run the query without the variable $sql_table (specifying that the table is called 'sitep_Home'), the query accepts the table. It then doesn't actually update the table, and I suspect it's because of the WHERE argument that also uses a variable.
Can anyone see what I'm doing wrong here?
try to use $sql_table as '$sql_table' if you are sure that this contain a right table name.
Like you are using other column's value
Check if this can help!!
Dump/log your query before executing it - the problem should be quite visible after that (I suspect some additional characters in the table name).
Couple of things:
you should never trust your users and accept everything they'll send you in $_POST, use whitelist for the fields you'd like to update instead
your code is vulnerable to SQL injection, I recommend to use some framework / standalone library or PDO at least, avoid mysql_query which will be deprecated in the future. Check this to get some explanation http://www.phptherightway.com/#databases
Table names are case sensitive in MySQL. Please check if there is mistake in the case.
You have to surround name of mysql table in query in this `` qoutes. When you dinamically create mysql table it is very important to trim($variable of mysql name table) before create, because if "$variable of mysql name table" have space in the edns or in the start mysql not create table. And the last when you call dinamically $variable of mysql name table in query you have to trim($variable of mysql name table) again.

Fetching a specific SQL column's content

I have a MySQL table containing columns for user IP (IP) and their name (Name). I want to compare the user's browser IP to the IP column the SQL table, and save their name to a PHP variable $name should an IP match be found.
I'm using $ip = $_SERVER['REMOTE_ADDR'] to save the browser's IP. How would I go about comparing this variable to the IP addresses in the SQL database? I tried $getname = mysql_query("SELECT Name FROM MyTable WHERE IP=$ip"); but this seems to return a Resource ID.
My apologizes if the question seems awfully elementary; I'm rather new to SQL (and PHP, for that matter). Also, I'm not in need for a secure way of authenticating for this one.
Use below code, after firing the query you have to iterate the result to get the output.
$getname = mysql_query("SELECT Name FROM MyTable WHERE IP='$ip'");
if(mysql_num_rows($getname)>0)
{
while($row = mysql_fetch_array($getname))
{
echo $row['Name'];
}
}
wrap the value of IP with single quote.
mysql_query("SELECT Name FROM MyTable WHERE IP='$ip'");

Storing temp values in session array to use in mysql query

I have a view that needs updating with a list of id's. So I am storing the values that have been selected to remove from the view in a session variable that then goes into the mySQL query as below. Then when the form is reset the values are also reset out of the array.
But its not working... this is what I've got.
Any help would be appreciated.
if($_POST['flag']=='flag'){
//collect deleted rows
$_SESSION['delete-row'][] = $_POST['idval'];
//Split session array
$idavls = join(',' , $_session['delete-row'];
$sqlDelete = "CREATE OR REPLACE VIEW filtetbl AS SELECT * FROM `".$page['db-name']."`.`leads_tbl` WHERE ".$_SESSION['filter-view']." AND `lead_status` = '1' AND `lead_id` NOT IN (".$idvals.") ORDER BY `lead_added`";
$result = mysql_query($sqlDelete);
if($result){
echo true;
}
else{
echo mysql_error();
}
}
$_session isnt the same as $_SESSION for a start.
Also dont use mysql_query or similar (because it isnt safe) use PDO
This is hard to correct without more information (and there are several errors - probaby cut and paste) so I'll pull apart one by one and you can go from there.
1 - $_SESSION['delete-row'][] = $_POST['idval'];
If 'idval' comes from multiple inputs (i.e. ) then it is already an array, and you should have $_SESSION['delete-row'] = $_POST['idval']; If you are looping in an array of inputs (i.e. trying to append for many posts from then it is correct)
2 - $idavls = join(',' , $_session['delete-row'];
$_SESSION (you said this was a type) and you also need a bracket/bract ar the end
$sqlDelete = "CREATE OR REPLACE VIEW filtetbl AS SELECT * FROM ".$page['db-name'].".leads_tbl WHERE ".$_SESSION['filter-view']." AND lead_status = '1' AND lead_id NOT IN (".$idvals.") ORDER BY lead_added";
Firsly this is very insecure as pointed out by allen213. Even if you don't use PDO to make safe the variable, please cast all the inputs as (int) assuming the IDs are integers, or at least wrap the input in mysql_real_escape_string().
Secondly, the logic in the question doesn't quite make sense. You say you want to remove IDs from the view, but what you are doing is recreating the view with only those IDs in $_SESSION['delete-row'] removed - so this may re-introduce IDs previously removed from the view. You'd actually need to keep $_SESSION['delete-row'] and keep adding to it to ensure the next time the view was created, then all the IDs are removed.
I hope that helps. If not, more code may be required (i.e. the form you are using the send data, anythign else that affects sessions etc.

Categories