
Phi11W
Members-
Posts
166 -
Joined
-
Last visited
-
Days Won
13
Everything posted by Phi11W
-
I am getting an error while creating the link.
Phi11W replied to maviyazilim's topic in PHP Coding Help
Remember that PHP does not write HTML. It writes strings that just happen to contain some words that your web browser can do something "clever" with. You are creating a string literal, and you've chosen to use the single-quote to wrap around it. So far, so good. But your literal contains single quotes as well, and those are confusing PHP. You either need to escape your embedded single quotes or, because HTML doesn't care which you use, use double-quotes in the HTML instead: // Either (using double-quotes) echo '<a href="icerik.php?=icerik' . $goster['icerik_id'] . '">' . $goster['baslik'] . '</a>'; // or (with escaped single-quotes) echo '<a href=\'icerik.php?=icerik' . $goster['icerik_id'] . '\'>' . $goster['baslik'] . '</a>'; // or, my personal favourite printf( '<a href=\'icerik.php?=icerik%s\'>%s</a>', $goster['icerik_id'], $goster['baslik'] ); Regards, Phill W. -
I assume you are not using "sort" in it's technical sense here. There is no sorting required in any part of this, which looks like a Homework Assignment, to me (so you don't get the answer straight away! 😀). As an aside, I would say that this function should take three parameters, not two. 1. The array itself, 2. the lower limit of values you want to look for, 3. The upper limit of values you want to look for. Anyway ... Within the function, you'll need a local variable in which to store the calculated total. Remember to start this off at zero. Then, loop through the elements of the array and compare each element to the lower and upper limits (parameters). If the element value is greater than or equal to the lower limit and less than or equal to the upper limit, then add the element value to the total. After the loop, return the total. Regards, Phill W.
-
PHP CSV Upload - Some rows in CSV file aren't in database
Phi11W replied to KN1V3S's topic in PHP Coding Help
Pull the data back out of the database and copy it into your favourite spreadsheet program (e.g. MS Excel). Then do the same with the data from the original file. Put the two lists side by side on a single worksheet, sort the two lists and compare visually. It shouldn't take more than a few minutes to find the ones that appear in one list and not the other. Regards, Phill W. -
How to connect Oracle database in PHP from external network?
Phi11W replied to Abrar's topic in PHP Coding Help
If you're building an API, then it should be built and run on your own infrastructure (servers). If this is the case, then your Oracle database should absolutely not be exposed to the external network. Anything on your machine(s)? That can be trusted. (Mostly). Anywhere else to your machine? That's not trusted. Only the Web URL should be made available to the client and that will require you to have a Web server process (again, running on your infrastructure) that will receive those requests and process them as required. Do not try to use your database "like" a web server. Web servers have all sorts of clever "stuff" in them to protect themselves (and your Data) from the Ne'er-do-well's "out there" on the Wild, Wild Web. Your database does not. Regards, Phill W. -
Recursive function file_put_contents file header issue
Phi11W replied to jarvis's topic in PHP Coding Help
At the point in your function where you're about to append some data into the file, test whether the file exists. If the file does not exist, then write the column headers into the file. Then, append the data into the file, regardless of whether you just wrote the headers or not. In the second and subsequent calls (recursive or not), the file will exist and so the headers will not be repeated. Regards, Phill W. -
prevent empty data from inserting into my database.
Phi11W replied to sashavalentina's topic in PHP Coding Help
There is no "Magic" here and, in the World of Programming, very little happens "automatically". Your code reads every row in the file, [poorly] constructs a SQL insert statement using the values in that row, and then executes that insert statement, thereby adding the row into the database. You need to change your code and add tests into it that will reject any row that contains data items that do not conform to your Business Rules (e.g. "Order Id cannot be zero"). How you report these failures back to the User is for you to decide. Regards, Phill W. -
prevent empty data from inserting into my database.
Phi11W replied to sashavalentina's topic in PHP Coding Help
It's called Data Validation. Just because the data comes from a file doesn't mean that your application should blindly "trust" it. The data is still coming from an untrustworthy source (i.e. anything that doesn't run on your own servers). Read each line from the file, validate the data, store only what "fits" and reject what doesn't (or rollback your Transaction to throw the whole lot away at the end of a "failed" upload run; YMMV). You are wide open to SQL Injection attacks. Read up about Parameterised Queries. Obligatory XKCD Reference - Little Bobby Tables. Regards, Phill W. -
Depends on how many "levels" you need to work with. If you only need, say, immediately related parent or child records, or even as far as grandparent or grandchild, you can do that with a regular query, just joining the table to itself the required number of times. select ... from table1 parent inner join tabel1 child on parent.child = child.parent inner join table1 grandchild on child.child = grandchild.parent ; But, as soon as you start getting arbitrary depth of nesting, a CTE is the way to go. Also, bear in mind that you want some way of stopping this recursion. You have no guarantee that, eventually, someone won't manage to create a loop in your data! (record1 -> record2 -> record3 -> ... -> record1). You can do this in the query itself or, perhaps better, with something (i.e. a Trigger) in the database to detect and reject the creation of such loops. You might remember to write your query with this Gotcha! in mind, but there's no guarantee that the next Developer to work on this Application will do the same! Regards, Phill W.
-
Over the lifetime of this (or any other) Application, you will spend far more time reading its code than you will writing any of it so go for whichever form expresses your intention most clearly. Personally, I'd go with the former or, perhaps, an even more concise one: if ( ! isset( $_SESSION['user'] ) ) exit ; if ( 'SiteOwner' !== $_SESSION['user'] ) exit ; I'm not sure of the context in which this runs - perhaps a redirect to another page might be more appropriate than the "exit"? YMMV. Regards, Phill W.
-
Excellent! If anyone asks, you're now applying the Principle of Least Privilege, getting your application work with the minimum level of permissions - just what it needs and nothing more. Also, you are now qualified to laugh openly at anyone that runs their entire Application as root. 😉 Regards, Phill W.
- 3 replies
-
- 1
-
-
- permissions
- write and execute
-
(and 1 more)
Tagged with:
-
This is a fundamental difference between files and directories. On a file, the execute bit makes the file .. well .. executable. On a directory, the "execute" bit makes the directory "navigable", i.e. you can get "into" it. At present, you can see that the directory exists - you can 'r'ead it in a listing of the parent directory - but you cannot navigate into it. To do that, the directory must have its Execute bit set. More typical permissions on a directory would be 750: User:rwx Group:rx Other:(None) This link explains it better, albeit talking about NFS and UFS, but the principle applies to all types of file system. It works because you're using the Group-level permissions, which allow you to delete things. You should leave it owned by www-data: that account is the owner of this data and works with it all the time; you're just popping in and out now and again (and, if you were to move on to another job, deleting your account would not take down the whole system!) Regards, Phill W.
- 3 replies
-
- 1
-
-
- permissions
- write and execute
-
(and 1 more)
Tagged with:
-
filter_var or htmlentities() or htmlspecialchars()
Phi11W replied to hany's topic in PHP Coding Help
In a Client-Server application, like this, you have to consider two, very separate Environments: The secure Environment, in which your code runs and your database lives. Here, you can Trust everything. Everything is stored in "proper" Data Types. Life is Good. 🙂 The unsecure Environment, which is everything outside the secure Environment. This includes the User's browser and even the TCP/IP channel between your server and that browser. Here, you can Trust nothing. All data is encoded into Character Representations of itself (Users cannot enter "numbers" or "dates" as a computer or a database would store them). The trick, then, is how to get Data back and forth, between the two? For data coming "in", you have to clean, verify and decode those data to make them safe to be "admitted" into your "Inner Sanctum", most importantly, your database. This is basic, defensive programming-type stuff, plus things like Prepared SQL statements to minimise database vulnerability. That's where filter_var can help (once you've figured out what sort of Wee Beastie the datum is - trying to do numeric range checks on the letter 'q' always causes "fun" in testing. For data going "out", you have to encode those data to make them safe for the browser receiving them. That's what things like htmlentities and htmlspecialchars come in, to defend against Cross-Site Scripting (XSS) Attacks and other things. You should also consider more general things, like date and number formatting, which different User communities may want presented differently. Here's a comprehensive StackExchange Accepted answer on the subject. Regards, Phill W. -
Here's an idea to try and get your head around ... You cannot click on anything in PHP. PHP is a server-side technology so you can only get it do anything by sending it an HTTP request, by loading a URL, submitting a Form or sending it an AJAX request. Clicking is a client-side thing, usually supported by Javascript code that runs in your browser (and often sends AJAX requests under the covers). Fire up the "Developer Tools" in your favourite browser and step through the Javascript code as it runs. Regards, Phill W.
-
You don't need JSON data (unless you actually want to store JSON data). Use two database connections - one to the local database, another to the cloud one - then loop through the data from the local one and insert it into the cloud one: $insertDB -> prepare('insert into cloud_users values ( :id, :username )'); $readDB -> prepare('select id, username from users order by 1'); $readDB -> execute(); while ( $row = $readDB -> fetch() ) { $insertDB -> execute( [ 'id' => $row['id'], 'username' => $row['username'] ] ); } Regards, Phill W.
-
I'm guessing that's because you told it to? while( $r = mysqli_fetch_row( $result ) ) { echo "<option data-location_name='$r[1]' data-location_phone='$r[2]' value='$r[0]' selected> $r[0] </option>"; // ^ ^ ^ ID!! // | | ID // | Phone // Name // } Trying putting the name ($r['location_id']) inside the option element, not the id or, rather, whatever happens to be the first column that your query retrieves ($r[0]). Regards, Phill W.
-
Taking these statements in order: $rec = mysqli_query( $db, "SELECT FROM joborder WHERE id=$id" ); This tries to execute a SQL query and puts the result - hopefully a set of results - into $rec. The function can also return false if its execution fails - which it will because your SQL in invalid. (What were you hoping to get from the joborder table?). I'll gloss over your SQL Injection Attack vulnerability for now. $record = mysqli_fetch_array( $rec ); Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in line 8 So now PHP is complaining that you're passing a Boolean value (false) as the first parameter to this function. Fix your SQL and try again. 🙂 Regards, Phill W.
-
You have an array containing the field names that were passed into the function. That array is used to build the SQL statement so those columns will be returned in each row. Now, for each row in the returned data, you need to loop through your fields array and pull out each value from the row, by field name, something like this: while( $row = $results->fetch_assoc() ){ $dlm = ''; foreach( $fields as $field ){ echo $dlm . $row[ $field ]; $dlm = "\t"; } } Regards, Phill W.
-
Personally, I prefer to have my SQL clean and self-contained but then I don't have to work with WordPress. YMMV. Here's one way: public function wpquery_select($conn,$sql,$fields){ $sql = replace($sql,'*',implode(',',$fields); <-- Assumes your query has "select * ..." $results = $conn->query($sql); . . . Regards, Phill W.
-
Thank you for posting your database's root password for the whole world to read. Go and change it right now. Stop using the root user in your Application code. Create dedicated accounts for each of your Applications and grant these accounts appropriate permissions. Always keep the biggest and best tools to yourself (so that you can sort out the mess made by other people or programs). Stop using Reserved Words as table / column names (e.g. "user" & "password"). Doing so will come back to bite you, at some point. Don't store the user's actual password. Instead, take the entered password, put it through your favourite, one-way, hashing algorithm and store the result of that. (When the user is logging in, take the entered password, hash it and check that value against what's in the database. Read up about Prepared Statements as a way to protect yourself against SQL Injection Attacks. Obligatory XKCD Reference: Little Bobby Tables. Regards, Phill W.
-
Which file? Would you expect both the load() and save() method [of this subclass] to all the work to find out which file they needed to work with? No. What might be more "normal" would be to tell the object which file is should "save" itself to, i.e. you would pass the load() and save() methods the path to the target file. But then you have another problem ... This is a Box. A Musical Box, wound up and ready to ... no; that's a different story. This is a Box. It will be one of many Boxes and each of these will need to load() and save() themselves to/from somewhere (having one file per box might be OK, but could make for a lot of files!) A typical pattern I've seen to handle this is to pass each method something that it can read from or write to - a file stream is commonplace, but it really depends on how you intend to store your data ab out each box. Regards, Phill W.
-
How to echo option i selected, because right now it shows blank
Phi11W replied to Lukeishen's topic in PHP Coding Help
You structure looks wrong to me. You have multiple form elements, each of which contains one select element with two option elements. I would expect there to be one form element, which contains one select element, which contains one or more option elements. echo( '<form method="POST">' ); echo( '<select name="inv">' ); if( mysqli_num_rows($result) ) { echo( '<option>' . $row["rizikos_lygis"] . '</option>' ); while( $row = mysqli_fetch_array($result) ) { printf( '<option value=\'%s\'>%s %s</option>' , $row["sugeneruoja"] , $row["pavadinimas"] , $row["sugeneruoja"] ); } } echo( '</select>' ); echo( '<input type="submit" name="submit" value="Apskaičiuoti">' ); echo( '</form>' ); Regards, Phill W. -
As Brand says, try the assembled SQL manually and see what the database is objecting to. Some other thoughts: 1. You're wide open to an SQL Injection Attack. Obligatory XKCD Reference - Little Bobby Tables. Less severely, you're effectively excluding anybody with an apostrophe in their name, e.g. "Peter O'Toole", from registering with your site! Not that you'd be the only one, according to IrishCentral. Why is this? Because in your PHP code you're building a String value that just happens to contain some text that your database should be able to make sense of. By blindly bolting things together in this way - easy though it might be - you're not following the Rules that SQL expects. Look into Prepared Statements as a way to correct this. 2. Never use "Select *" in Production code. Both of your checks are pulling every field in the username table. That might be fine now, when you only have a handful of small fields to worry about but sooner or later, someone [else] is going to think it's a "great idea" to add a BLOB field into this table that contains terabytes of video profile for each user. Suddenly, your user check, which used to be really quick, is having to haul all of that data back across the network, even though its not interested in a single byte of it! Always specify the fields that you want to work with explicitly. All that said, I wouldn't perform the check this way at all. What you have here is a potential Race Condition. Computers are fast. Really fast. It's possible that, after checking for duplicate username and email but before doing the actual insert, someone else could get in and insert the same values into the database. Now you have duplicate user records or two people using the same account. Nightmare. Instead, get the database to do the heavy lifting for you: Add a unique index on username.email. Add a unique index on username.username. Remove both the check queries and just attempt the insert. If the user tries to reuse an existing username or email address, you'll get an error that you can handle in your code. Finally, your PHP code, as given, is difficult to read. You'll spend far more time reading code than writing it so start to think about readability now. (I very nearly "went off" on one because you were building a SQL string instead of executing it. I found the execution, eventually, way over to the right, off the edge of my screen!) Think about code readability, not least of which "one statement per line" and "indenting". With that in mind, let's take another look at your code: /* Register and check username and email is exist or not */ if (isset($_POST['submitted'])) { $username = $_POST['user']; $email = $_POST['email']; $first = $_POST['first']; $last = $_POST['last']; $password = $_POST['password']; $check_user = "SELECT * FROM username where Username = '".$username."'"; $check_email = "SELECT * FROM username where Email = '".$email."'"; $check_user2 = mysqli_query($GaryDB, $check_user); $check_email2 = mysqli_query($GaryDB, $check_email); if(mysqli_num_rows($check_user2) > 0) { $taken_user = "→ Sorry, Username is taken"; } elseif (mysqli_num_rows($check_email2) > 0) { $taken_email = "→ Sorry, E-mail is taken"; } else { $register = "INSERT INTO username (Username, Password, FirstName, LastName, Email) VALUES ('$username','$password','$first','$last','$email')"; $insert = mysqli_query($GaryDB, $register); /* } --- Closing brace - wrong place! */ if ($insert) { $insert1 = "successfully added"; } else { $insert1 = "Failed to added"; } } /* --- Closing brace SHOULD be here */ Note that, because of the misplaced braces (which are far easier to see with the code nicely laid out) the code is always passing through the "if($insert)" test, regardless of what else it does. It should only go through that bit if it's tried to do an insert, which it will with the closing brace moved as I've described. Regards, Phill W.
-
I'm not surprised you can't see what's going on wrong, with all the chopping and changing back and forth between HTML and PHP. Keep it Simple: <?php if(isset($_POST['Submit'])){ $name=$_POST["Name"]; } . . . $sql = 'SELECT * FROM dirCsv_500'; /* Added a missing ";" here */ if (!empty($name)) { $sql .= " where name like '%".$name."%'"; /* Added string concatenation */ } ?> /* Removed an extraneous ";" here that's actually in the HTML, not the PHP */ I think I can see what you're trying to do, but that's just not how you write PHP. You can "duck in and out" to embed bits of HTML in between the PHP code, but you can't embed bits of PHP code in between the PHP code! There's other things to worry about here as well. From a database perspective, your code will perform poorly on a large table, given the leading wildcard in your search criteria, e.g. '%fred%'. The database is unable to use an index for this and will scan the table serially (i.e. slowly). Even before that, though, you have an even bigger problem - you are wide open to a SQL Injection Attack. Obligatory XKCD Reference - Little Bobby Tables. Look at using Prepared Statements for your SQL to [partly] protect yourself against this. Regards, Phill W.
-
Does the "3rd Party Website API" offer a method by which you can retrieve the data in the order you want? That would be easiest. Failing that, you're just going to have to take the data as it is provided and then do the sorting yourself. If you're really lucky, the dates will already be in a sortable format ... Regards, Phill W.