How can i execute php script from mysqli database - php

Please anybody help me. I want to execute php script from mysql database. My plan is so many if(),else if() statement will be execute. I had used eval($row['data']) statement in to while() loop and it's worked. But only first one.not at all.
My code as below.
$conn = mysqli_connect();
$sql = "SELECT * FROM transaction ORDER BY id ASC";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0 ){
while($row = mysqli_fetch_array($result)){
eval($row['tran_php']);
// echo eval($row['tran_php']);
}
}
Here is only first one does work which one is if(). Do you have any solution to work all about the else if() statement end of the if() statement?

You have ever heared "eval is evil"? Its true. eval is a development nightmare and a good indicator for doing something wrong.
Only a idea. Do not store the PHP code in database. Store it as files, link to it in DB (filename and/or id) and include it by the regular way.
But always remember this can be a security issue if the code comes from users!
The best way is to encapsule everithing by a UI where the user inputs his stuff and PHP handles it for example by a Parser, build by you.
Why there is the need to do it with PHP-Code like you?

Related

Can't Use Variables in mysql_query()?

This is about as basic as it gets guys and girls.
I have a very simple script that just will not work. I call the database and test it's connection, I do a query, store the result, and print the result.
The problem is that I can't seem to use any variables in my SQL statement.
Here's the code:
<?php
$rest_name = $_GET['rest_name']; // outputs 'Starbucks'
$test = mysql_query("SELECT code_id FROM table_code WHERE restaurant = '$rest_name'");
/* I've also tried these as well
$test = mysql_query("SELECT code_id FROM table_code WHERE restaurant = '".$rest_name."'");
*/
$mark = mysql_result($test,0);
echo $_GET['rest_name'].$mark;
?>
I echoed the query and it looks fine and run fine in the database. The $rest_name variable echos fine. The $_GET['rest_name'] echos fine. I am lost and confused on this.
1 - You can start with this.
$test = mysql_query("S....") or die(mysql_error());
This way you will see what error you are getting.
2 - you might want to avoid using a variable provided by the user in your query
$rest_name = mysql_real_escape_string($_GET['rest_name']);
otherwise user can insert their own sql commands;
3 - mysql_xxx functions are being deprecated, you might want to research pdo or mysqli to see how the new methods work.
Verify that you have a valid result set returned by msyql_query
$test = mysql_query("SELECT ... ");
if (!$test) {
die(mysql_error());
}
(It's possible you aren't connected to the MySQL instance, you are in the wrong database, the user you are connected as doesn't have permissions, etc.)
Check the resultset, before you use it.
NOTE: Don't use the mysql_ functions, use mysqli or PDO instead.

how can i get a field on a mysql table?

Im a php/mySQL newbie and am trying to get the hang of it. I have code to detect whether i get a username/password match, and now im trying to get the userid field so i can update the record. Heres what I have so far:
$sql = "SELECT username FROM users WHERE username='$username' AND password='$password'";
$result = $link->query($sql) or die(mysqli_error());
Using print_r($result) shows that there is an item, but im lost from here on out.
Try this.
$sql = "SELECT username FROM users WHERE username='$username' AND password='$password'";
$result = $link->query($sql) or die(mysqli_error());
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$userID= $row['username'] ;
// If you need other field as userID just change the sql and the index of $row according to that.
}
EDIT
If you want to get only one row.
if($result->num_rows==1)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
$userID = $row["username"];
}
Perhaps this will help. In any programming language, running an SQL query is going to consist of these steps:
Build the text of the SQL statement that you want to run.
(Optional) If your statement involves the use of parameters (or "placeholders"), prepare an array of the parameter-values that are to be substituted for each of them.
("Prepare" and...) "Run" the query, on some previously-opened "database connection." (In your example, "$link" must correspond to that connection.) This gives you a handle (you called it "$result") that corresponds to the zero-or-more rows that were returned by that query.
Now, use that handle to retrieve each of these rows, one at a time, until there are no more or until you're tired of doing it.
(Optional) Be neat and tidy and "close" the handle, thus indicating to the database system that it can discard all of the resources it was using to furnish those rows to you.
"Those, in simple terms, are the basic steps that every program in the known universe are going to go through," and if you now browse again through the PHP documentation, you'll see that there are functions that correspond to each of these steps. Browse through the chapters you've been reading and see if you can now match the up to the scenario I just described. HTH...

PHP MySQL update a row that has been selected

This is something I used to do in Java, I was wondering if there is an equivelant in PHP.
In Java, I'd do something like this (pseudo only as I've gotten rusty in the last year or so):
preparedStatement = new StringBuilder("SELECT something FROM somewhere");
ResultSet rs = preparedStatement.executeQuery();
while(rs.next())
{
if (someTest)
{
rs.updateRow[1]="someNewValue";
}
}
This is wide of the mark syntactically (and I bet it won't compile) but I hope it explains the kind of thing I was able to do. Not sure if it saved an actual DB query from being run but it did make my code alot cleaner.
So in PHP, I have something like this:
$query = "SELECT something FROM somewhere";
$result = mysql_query($query, $db);
while ($row = mysql_fetch_assoc($result))
{
if (someTest)
{
//how can I update this row without coding another query?
}
}
Is there an equivelant to this in PHP?
I'm using the vanilla mysql db methods, not mysqli or that other one (pod or something?) but I think I'd be safe to use mysqli on our servers if I need to.
Any help appreciated
Nope, you could however use mysql_fetch_object with a custom classname, and define a save() method on it that will run the update query for you. Keeps the logic out of the loop and in a Model for that data. Or use an full-blown ORM library which does this kind of thing.
As far as I'm aware, you can't update the row without running another query such as:
UPDATE table SET column1="value" WHERE (column2="value");

PHP MySql Select statement not working... Any advice?

[UPDATED] with new code "sql_real_escape_string()"
[UPDATED] if anyone wants to look at the site its at Test site
[UPDATED] with the while code showing any results via echo
Hello All,
I have looked at many posts on this matter, but simply cannot understand why the following code doesn't work:
$username = $_POST['username'];
// get the record of the user, by looking up username in the database.
$query = sprintf("SELECT UserName, Password FROM userlogin WHERE UserName='%s'", mysql_real_escape_string($username));
$result = mysqli_query($dbc, $query) or
die ("Error Querying Database for: " . $query .
"<br />Error Details: " . mysql_error() . "<br/>" . $result);
while ($row = mysqli_fetch_assoc($result))
{
Echo($row['UserName']);
}
The Code seems to be correct... the database is working perfectly (for input purposes) and the connection is a shared connection applied with require_once('databaseconnection.php'); that is working for the registration side of things.
like normal I'm sure this is something simple that I have overlooked but cannot for the life of me see it!
I do not get any error messages from the myssql_error() its simply blank.
any help would be much appreciated.
Regards
Check the username you try to query as it might be empty. Do you really use a post-request to run that script? How do you verify that it does not work? What do you do with $data after the query?
If just nothing seems to happen it is likely your query did not match any record. Check for whitespace and case of the username you are looking for.
Mind those warnings:
Use a prepared statement or at least sql-escape any user-input before using it in sql.
Don't use die in serious code only for debugging.
The $data will contain a result object. You need to iterate over it using something like mysqli_fetch_assoc($data).
Also, you can interpolate variables directly into double quoted strings - i.e. UserName='".$username."'" could be written more cleanly as UserName='$username' rather than breaking out of the string.
Also, please sanitize your input - all input is evil - using mysqli_real_escape_string() function. You've got a SQL injection exploit waiting to happen here.
Bear in mind that it's a very good idea to validate all data to be inserted into a database.
Very often you have problems with query itself, not implementation. Try it in phpMyAdmin first and see if there are any problems.
Check server logs.
BY THE WAY: Never put variables from POST to query! That's definitely a SQL injection'
You might have some issue with the query.
Have you Tried to echo the $query and run that directly with mysql client or workbench?
This piece of code seems ok. That is, if $dbc contains an actual database connection. But the choice of naming that variable $data while the function actually returns a result object or a boolean, indicates that you may process the data wrong.
If that is not the problem, we'll definately have to see more code.
Try printing $data variable instead of printing only query. Check, whether you are able to get any error messages. If you could see any data then you should use mysql fetch function to iterate things. Try it.

PHP sql with foreach loop variable problem

This is really getting frustrating. I have a text file that I'm reading for a list of part numbers that goes into an array. I'm using the following foreach function to search a database for matching numbers.
$file = file('parts_array.txt');
foreach ($file as $newPart)
{
$sql = "SELECT products_sku FROM products WHERE products_sku='" . $newPart . "'";
$rs = mysql_query($sql);
$num_rows = mysql_num_rows($rs);
echo $num_rows;
echo "<br />";
}
The problem is I'm getting 0 rows returned from mysql_num_rows. I can type the sql statement without the variable and it works perfectly. I can even echo out the sql statement from this script, copy and paste the statement from the browser and it works. But, for some reason I'm not getting any records when I'm using the variable. I've used variables in sql statements tons of times, but this really has me stumped.
Try trimming and mysql_real_escape_string on your variable.
Check the source code of what is being echoed out and try to copy and paste that into PHPMyAdmin or something similar.
file includes newlines in the array elements. This may explain why it works when you copy the browser output but not in the script. You can try either:
$file = file('parts_array.txt', FILE_IGNORE_NEW_LINES);
or:
$sql = "SELECT products_sku FROM products WHERE products_sku='" . trim($newPart) . "'";
Note: Even though you're importing from a file of your own making, you can never be 100% sure that inject-able data hasn't been inserted into it. You should make sure to properly escape any data with mysql_real_escape_string. Even better would be using PDO prepared statements instead.
Obviously your code does something different than you expect. Running a successful query, for one: you don't check the return value of the mysql_query call, so you cannot be sure the query executed ok.
My idea:
dump your sql statement from the foreach
check the return code of the mysql_query
What does your parts_array.txt file look like? Do SKU numbers contain the ' character?
Can you please try this:
$file = file('parts_array.txt');
foreach ($file as $line_num => $line)
{
$sql = "SELECT products_sku FROM products WHERE products_sku='$line'";
echo $sql;
$rs = mysql_query($sql);
$num_rows = mysql_num_rows($rs);
echo $num_rows;
echo "<br />";
}
You might want to check for a mysql_error. It sounds like you've already verified the variable and have copied the query into a database interface like PHPMyAdmin or Query Browser, but if you haven't, I would recommend that.
After, verify that a very basic query will work, like SELECT * FROM Products. That will tell you if there is a problem outside of the query.
Overall, I would say the strategy would be to break the problem down into possible problem areas, like database, connection, query, errors, etc. Try to eliminate them one at a time until the problem is apparent. In other words, list the possibilities and cross them off one at a time.
I've encountered problems like this before; the trick is usually to start echoing things until you see the problem, and don't work off of assumptions.
I know this is pretty old now- but I'd like to help out others who may also be facing a similar problem with SQL statements that need to contain a potentially infinite number generated search parameters.
The code in the askers question is perfectly valid (for the avoidance of doubt) [see below]:
$file = file('parts_array.txt');
foreach ($file as $newPart)
{
$sql = "SELECT products_sku FROM products WHERE products_sku='" . $newPart . "'";
$rs = mysql_query($sql);
$num_rows = mysql_num_rows($rs);
echo $num_rows;
echo "<br />";
}
Their problem lies in the formatting of their text file ('parts_array.txt'). The root cause of the issue can be tracked down by dumping the information sent back by the server. Alternatively- they can try writing an SQL query in PHPMyAdmin and pasting in some or all of the data in their text file. MySQL will happily torment them until they find the problem.
For those trying to implement a variable based SQL query- the above is the way to go.
If you are trying to get data from an array, instead of a text file- you could do something like the following:
foreach ($array as $array_stuff)
{
$search_query = "SELECT * FROM table WHERE id='" . $array_stuff . "'";
$rs = mysqli_query($database_connection, $search_query);
$table_rows = mysqli_fetch_assoc($rs);
echo $table_rows['id']." - ".$table_rows['desc'];
echo "<br />";
}
/* free result set */
mysqli_free_result($rs);
This would output your data like this:
1001 - data 1 1002 - data 2 1003 - data 3
Note: The use of "mysql" functions are actively discouraged by MySQL. Therefore the second example I have given above is more up-to-date with current technologies, and using "mysqli" instead.
Also important
If you are here from a Google search as a result of trying to get data from a database, using a complex SQL query- you might have already tried to do something like the example below (or be considering it).
Do not attempt to write a variable based SQL query as per the example below. It won't work and will be incredibly frustrating.
Based on recent technological advancements- the second example I have given (using "mysqli") is the correct way (if there is one) to achieve this.
Bad example:
if ($search_result = mysqli_query($dbh1, "SELECT FROM sic_codes WHERE id = (".foreach ($_POST['SIC_Codes'] as $sic_codes) {echo "'".$sic_codes."' OR id = '',";})) {
/* fetch associative array */
while ($search_row = mysqli_fetch_assoc($search_result)) {
echo $row["id"]." - ".$row["desc"]."<br/>";
}

Categories