I am attempting to get a function working on an old php based application, autonomous lan party. It is based on php4 but it does work with what I want it to do on a php5 server (it is also only used in an intranet environment). I'm adding an accounting add-on from here. I can understand php, but still somewhat rusty.
Below is a small sample of code I'm stuck with...
<FORM ACTION="<?php echo $_SERVER['PHP_SELF']; ?>" METHOD="post" NAME="accounting" ID="accounting">
<strong>user: </strong><br>
<SELECT NAME="userid[]" SIZE="5" class="formcolors" TABINDEX="1" MULTIPLE>
<?php
$data = $dbc->query('SELECT username,userid FROM users ORDER BY username');
while ( $row = $data->fetchRow()) {
$option = '
<OPTION VALUE="%s" class="formcolors">%s</OPTION>';
printf($option, $row['userid'], $row['username']);
}
$data->free();
unset($option, $data);
?>
</SELECT>
The problem is once it reaches te $data->free(); line, the script stops executing and supplies the error mentioned in the topic. If I comment it out (twice, there is a similar line) the script runs but once i submit the data I get another error in the logfile...
PHP Warning: mysql_escape_string() expects parameter 1 to be string, array given
I believe that error is because I've commented out $data->free(); so it's not able to get the correct result.
I've pasted the full code from the file at pastebin here (didnt want to fill this page up with all the other code).
Any help or assistance would be much appreciated. Everything else on the application works as expected.
If I understand correctly, $data is a mysql result.
To free the result from memory, try using mysqli_free_result() instead.
$data = $dbc->query('SELECT username,userid FROM users ORDER BY username');
while ( $row = $data->fetchRow()) {
$option = '
<OPTION VALUE="%s" class="formcolors">%s</OPTION>';
printf($option, $row['userid'], $row['username']);
}
mysqli_free_result($data->free());
unset($option, $data);
Related
I have a simple HTML form using json_encode to send a PHP variable (via value=) to a file and then using json_decode to extract and echo the results. I am battling to get the correct syntax or method to decode the json_decode in the object environment, required by Opencart. It works fine when I use the procedural method below.
I have attempted various syntax changes, but they return errors, so I believe that the syntax is incorrect, or my method cannot be done this way.
1st Code is the Procedural method that returns the correct result.
2nd code is the OOP method which fails. - (assume syntax is wrong.
Code Working:-
<form id="myForm" action="radio_result.php" method="post"
enctype="multipart/form-data">
<input type="radio" name="service" value="<?php echo
htmlentities(json_encode($service_onx));?>"> ONX
//additional code excluded.
radio_result.php // not all code shown
<?php
if(!empty($_POST['service'])) {
$service = json_decode($_POST['service'], true);
print_r($service);
Code failing:-
<form id="myForm" action="index.php?route=checkout/checkout"
method="post" enctype="multipart/form-data">
<input type="radio" name="service" value="<?php echo
htmlentities(json_encode($service_onx));?>"> ONX
checkout.php // not all code shown
$this->session->data['service'] = (isset($this->request-
>post(json_decode(['service'])))) ? $this->request->post['service'] :
"not_set";
$data['onx'] = $this->session->data['service'][0];
$data['eta'] = $this->session->data['service'][1];
Error result:-
Fatal error: Cannot use isset() on the result of an expression (you can
use "null !== expression" instead) in
C:\wamp64\www\catalog\controller\checkout\checkout.php on line 101
I would like to get the json_decode working in the Opencart framework
checkout.php so that I can use the reult further.
If I understand you correctly, you need an object?If so you can first do
$service = json_decode($_POST['service'], true);
And than cast this array as an object:
$serviceObject = (object) $service;
And you will have an object. Try it out.
Had a similar problem. Solved it by also encoding/decoding on base64. base64_encode(json_encode($string)) and the json_decode(base64_decode($string))
I've got a search function written in PHP/MySQL which works fine. What I want to happen is that when a user produces a search they can click a button which will submit the $id from the output to a table in my database.
I've copied my code below, the error is within the php echo in the form, it just displays the plain text of the php code.
Everything else works fine, I've tested this by setting value to "" and entering the id myself and then it works. I want it though to be a hidden input in future where the id automatically comes through from the search result. Multiple searches can be returned on the same page and this form is underneath each individual search result.
<?php
$conn = mysqli_connect("localhost","root","","users");
$output = '';
if(isset($_POST['search'])) {
$search = $_POST['search'];
$search = preg_replace("#[^0-9a-z]i#","", $search);
$query = mysqli_query($conn, "SELECT * FROM users WHERE main LIKE '%".$search."%'") or die ("Could not search");
$count = mysqli_num_rows($query);
if($count == 0){
$output = "There was no search results!";
}else{
while ($row = mysqli_fetch_array($query)) {
$id = $row ['id'];
$main = $row ['main'];
$postcode = $row ['postcode'];
$available = $row ['available'];
$email = $row ['email'];
$output .='<div><br><b>Player ID: </b>'.$id.'<br><b>Main:
</b>'.$main.'<br><b>Postcode: </b>'.$postcode.'<br><b>Available:
</b>'.$available.'<br>
<br>
<form action="request_player.php" action="post">
<input type="text" name="id" value="<?php echo $id ?>">
<input type="submit" value="Request Player">
</form>
</div>';
}
}
}
echo $output;
?>
<br> Back to your account
The issue Jay Blanchard highlighted and which you took a bit lightly - perhaps b/c you fear the distraction from your current problem - is actually pretty related to the issue you highlight in your question.
This btw. is nothing uncommon. In this little script you deal with at three languages: HTML, SQL and PHP. And all these are intermixed. It can happen that things jumble.
There are methods to prevent these little mistakes. What Jay highlighted was about how to encode a SQL query correctly.
The other problem is to encode a HTML string correctly. Let me highlight the part:
$output = '... <input type="text" name="id" value="<?php echo $id ?>"> ...';
In this PHP string you write "<?php echo $id ?>" verbatim, that means, this will echo'ed out then.
What you most likely meant was to write it this way:
$output = '... <input type="text" name="id" value="' . $id . '"> ...';
So this seems easy to fix. However, it's important that whether it is SQL or HTML, you need to properly encode the values if you want to use them as SQL or HTML. In the HTML case, you must ensure that the ID is properly encoded as a HTML attribute value. In PHP there is a handy function for that:
$output = '... <input type="text" name="id" value="' . htmlspecialchars($id) . '"> ...';
Or as the ID is numeric:
$output = '... <input type="text" name="id" value="' . intval($id) . '"> ...';
works similarly well.
You need to treat all user-data, that is all input - which includes what you get back from the database (!) - needs to be treated when you pass it into a different language, be it HTML, SQL or Javascript.
For the SQL Jay has linked you a good resource, for the HTML I don't have a good one at hand but it requires your own thoughtfulness and the will to learn about what you do (write) there. So sharpen your senses and imagine for each operation what happens there and how this all belongs together.
One way to keep things more apart and therefore help to concentrate on the job is to first collect all the data you want to output and then process these variables in a template for the output. That would prevent you to create large strings only to echo them later. PHP echoes automatically and a benefit of PHP is that you can use it easily for templating.
Another way is to first process the form input - again into your own variable structure - which is the programs input part and run first. Then follows the processing of the input data, in your case running and processing the database query. And after that you care about the presentation. That way you have common steps you can become more fluent in.
I hope this is understandable. It's full of further obstacles, but it pays to divide and conquer these programming problems. It will also help you to write more while you need to write less for that.
And btw., you don't need to switch to PDO, you can stick with Mysqli.
The reason it is happening is because you have put <?php echo $id ?> inside a string. You want to do the same thing you did elsewhere in your example: value="' . $id . '" It can quickly get confusing when you have single and double quotes happening together. You might be best off learning how to use PHPs multiline strings.
Also, <?= $id ?> is a useful shorthand for <?php echo $id ?> (although you don't want to use either here)
I have this problem I've been working on and can't seem to figure out. At the end of the day I would like to pass some values to a php script from a user form. I am working with files that were written a long time ago and have tried to treat the variable I am trying to pass the same way the original author tried to treat his own. Yet, despite trying to keep the approach the same, I am getting different results. Specifically, in the php script where I want to pass these variables, when I echo the value of $_POST['whole'] I get true or false, yet when I echo the value of $_POST['plotX'] I get a variable undefined error.
I apologize for the large amount of code, but I hope that if you search for terms queryDataCenterOfMass and plotX you will see what I am referring to.
The HTML portion comes out as follows. This is where the user selects true or false for 'whole' and true or false for 'plotX'. This is actually code from the webpage, php is used to generate this code, but I thought it would be simpler to paste the HTML.
<div id="wholeDiv" class="dynamicDiv">
<b>Whole</b>
<br>
<select id="whole" name="whole" class="atomTypeSelect">
<option value="">>>Select<<</option>
<option value="true">Yes</option>
<option value="false" selected="">No</option>
</select>
</div>
<div id="plotXDiv" class="dynamicDiv">
<b>Plot x dimension</b>
<br>
<select id="plotX" name="plotX" class="atomTypeSelect">
<option value="">>>Select<<</option>
<option value="true">Yes</option>
<option value="false" selected="">No</option>
</select>
</div>
The next part is the code that creates the submit button. The important part is, I belive, the onclick portion, which calls the function queryDataCenterofMass, which is given in a separate javascript file and I pasted below this.
<input type="hidden" name="table" value= <?php echo $_GET['schema'] ?>/>
<input type="hidden" name="queryName"
value= <?php echo $result[0]['query_id'] ?>/>
<input type='Submit' value=' Query Data' name='funcSearch'
onclick="queryDataCenterofMass(('<?php echo $result[0]['query_id'] ?>'),('<?php echo $_GET['schema'] ?>'),($('#firstFrame').val()) ,($('#lastFrame').val()) ,($('#skip').val()) , ($('#minX').val()) , ($('#minY').val()) ,
($('#minZ').val()), ($('#maxX').val()), ($('#maxY').val()), ($('#maxZ').val()), ($('#whole').val()), ($('#whole_pcb').val()), ($('#molName').val()),($('#atomTypeDll').val()), ($('#atomID').val()), ($('#molID').val()) ), ($('#plotX').val()), ($('#plotY').val()), ($('#plotZ').val()); false;"
class='dynamicParamButton'><br/><br/>
Here is the definition of queryDataCenterofMass. It seems to use a jQuery function to pass everything via post to comfunction.php.
function queryDataCenterofMass(queryId, schema, firstFrame, lastFrame, frameSkip, minX, minY, minZ, maxX, maxY, maxZ, whole, wholePcb, molName, atomType, atomID, molID, plotX, plotY, plotZ) {
$("#waiting").show(500);
$("#interface").hide(0);
// generate a random number to pass to function.php and append to the end of our gnuplot files to make them unique
var random_num = Math.floor((Math.random() * 1000000) + 1);
$.post('./function_files/comfunction.php',
{
random_num: random_num,
query_id: queryId,
simschema: schema,
firstFrame: firstFrame,
lastFrame: lastFrame,
frameSkip: frameSkip,
minX: minX,
minY: minY,
minZ: minZ,
maxX: maxX,
maxY: maxY,
maxZ: maxZ,
whole: whole,
whole_pcb: wholePcb,
molName: molName,
atomType: atomType,
atomID: atomID,
molID: molID,
plotX: plotX,
plotY: plotY,
plotZ: plotZ
},
function (data) {
$("#waiting").hide(0);
$("#results").show(500);
var img = document.getElementById("com_img");
img.src = "../queries/gnuplot_tmp_files/gnuplot_output" + random_num;
$('div#message').html(data).fadeIn({duration: 700});
$('html,body').animate({
scrollTop: $('div#message').offset().top
});
});
}
So that's it. I am not sure why in comfunction.php the variable $_POST['plotX'] is undefined yet other variables, including $_POST['whole'] are not. Solving this problem is very important to me... if there is some way I can better ask this question, or more information I can provide, please don't hesitate to let me know. Thanks.
The onclick line
($('#molID').val()) ),
Seems to have an extra bracket here. Which makes the onclick callback end early, before the plotX and other elements could be sent.
Protip/s:
- Bad idea to load mix such javascript eventhandlers inside HTML
- I simply loaded the html in a IDE which showed the syntax error (among others)
- use browser developer tools.
I'm new to PHP. Now i have a problem with files upload.
All files are moved, but It didn't store file's name to database.
and it didn't show error. I have no idea to fix this one. Please help me out.
<form method="post" action="index.php?insert_ads" enctype="multipart/form-data">
<input type="file" name="b1" id="b1"/>
<b>Link</b></br>
<input type="text" id="b1l" name="b1l" class="form-control"/></br>
<b>Home Small</b> <b style="color: blue;">100 x 100 px</b></br>
<input type="userfile" name="b2" id="b2"/><br>
<b>Link</b></br>
<input type="text" id="b2l" name="b2l" class="form-control"/></br>
<input type="submit" name="submit" value="Publish"/>
</form></br>
<?php
if(isset($_POST['submit'])){
$b1 = $_FILES['b1']['name'];
$tmp1 = $_FILES['b1']['tmp_name'];
$b1l = $_POST['b1l'];
$b2 = $_FILES['b2']['name'];
$tmp2 = $_FILES['b2']['tmp_name'];
$b2l = $_POST['b2l'];
move_uploaded_file($tmp1,"ads/$b1");
move_uploaded_file($tmp2,"ads/$b2");
$insert_posts = "insert into ads (b1,b2) value ('$b1','$b2')";
$run_posts = mysql_query($insert_posts);
}
?>
Notwithstanding any issues about using mysql_query or injection attacks, there are a number of things that could be going wrong here.
One option is that the query is executing, but you haven't assigned the $b1 and $b2 variables correctly. This would be the case if rows are being added to the database, but the rows are empty (e.g., SELECT b1, b2 FROM db.ads" returns rows of '',''); in that case, you probably just aren't extracting the name attribute from the $_FILES variable correctly. You can run var_dump($_FILES); to see more information about it and figure out what you need to get.
Another possibility is that the query is not executing. Again, this may be for a couple of reasons -- maybe (somehow) it's not reaching that point in the code. You can test that like so:
$insert_posts = "insert into ads (b1,b2) value ('$b1','$b2')";
echo $insert_posts; // if this shows up, you're running the next line also
$run_posts = mysql_query($insert_posts);
Another option is that your error reporting level is not capturing an error. A likely cause of this is that you have not connected to the database -- according to the mysql_query documentation...
If no connection is found or established, an E_WARNING level error is generated.
A E_WARNING level error will allow the program to continue to execute unless you have configured your program to behave differently.
Finally, you may have a syntax error (and indeed it seems you do -- VALUES, not VALUE); according to the documentation, mysql_query returns false on error -- it does not throw an error.
You can rig it to do so by testing for false and using the mysql_error function to get the error:
$run_posts = mysql_query($insert_posts);
if ($run_posts === false) {
trigger_error("Error in SQL!\n" + mysql_error(), E_USER_ERROR);
}
I have a simple code to add banners from admin panel to the index of the site. But the add function doesnt work correctly here is the form to add banner
<h2>Add Banner</h2>
<?php include ("../engine/config/config.php"); ?>
<form method="post" action="">
Clicks
<input type="text" name="click" value="0" style="width: 200px;" /> <div class="hr"></div>
Impressions
<input type="text" name="imp" value="0" style="width: 200px;" /> <div class="hr"></div>
LINK
<input type="text" name="url" value="http://" style="width: 200px;" /> <div class="hr"></div>
Size
<select name="razmer">
<option value='468x60'>468x60</option>
<option value='88x31'>88x31</option>
</select>
<div class="hr"></div>
Banner<br />
<input type="text" name="picurl" value="http://" style="width: 200px;" /><div class="hr"></div>
<input type="submit" name="submit" value="Submit"> <br />
</form>
<?
if($_POST['submit']) {
$click = $_POST['click'];
$imp = $_POST['imp'];
$url = $_POST['url'];
$razmer = $_POST['razmer'];
$picurl = $_POST['picurl'];
$sql = "INSERT INTO `banneradd` (click, imp, url, razmer, picurl, username) VALUES ('$click', '$imp', '$url', '$razmer', '$picurl', '')";
$result = mysql_query($sql);
echo "<div class='hr'>The Banner has been added, please go back to the index: <a href='view_reklama.php'> Index </a></div>";
}
?>
So it say it was added but when I go back ITS NOT. There is no error or anything, can someone help? Thanks in advance :)
Okay, there are way too many things wrong with your code, so if you're learning from a particular site or person... find a different source.
Don't open PHP with <?. This is the shorthand style. It is disabled on many if not most web servers, and for good reason -- because XML introduces its encoding using the same opening <? and it causes conflict. Always open your PHP with <?php. http://www.php.net/manual/en/ini.core.php#ini.short-open-tag
Don't use if($_POST['submit']), use if (isset($_POST['submit'])). Your current script should generate an error, but it's probably being masked because PHP defaults to not showing very many errors. It does trigger a warning, though, because you're checking if the variable (or rather array value) $_POST['submit'] is equal to true. In fact, that variable is undefined. Use isset() to check if a variable exists. http://php.net/manual/en/function.isset.php
Sanitize your user's input. If somebody typed a ' into any of your fields, your query would break. Why? Because in your query, you're placing your stringed values in single quotes, and any instance of another single quotation mark would break out of that. There is such a thing as magic quotes in PHP (which automatically escapes POST values), but it's absolutely awful, so please disable it. http://php.net/manual/en/security.magicquotes.php The best way to escape user input is with real escape functions (more on that later).
mysql_ functions are deprecated. Use PDO or MySQLi. If you're getting used to the mysql_ functions, it is easier to transition to MySQLi. For simplicity, I'll use the procedural style, but it's much better to go with the OOP style....
If you want to debug MySQL commands with PHP, you should format your queries carefully, print the error, and also print the computed query, because sometimes you need to look at the actual resulted query in order to see what is wrong with it.
That said, here's what I suggest:
<?php
error_reporting(E_ALL);
// Turn on all error reporting. Honestly, do this every time you write a script,
// or, better yet, change the PHP configuration.
$connection = mysqli_connect('host', 'username', 'password', 'database');
// Somewhere in your config file, I assume you're calling mysql_connect.
// This is a pretty similar syntax, although you won't need mysql_select_db.
if (isset($_POST['submit'])) {
$click = mysqli_real_escape_string($connection, $_POST['click']);
// This will escape the contents of $_POST['click'], e.g.
// if the user inputted: Hello, 'world'! then this will produce:
// Hello, \'world\'!
$imp = mysqli_real_escape_string($connection, $_POST['imp']);
$url = mysqli_real_escape_string($connection, $_POST['url']);
$razmer = mysqli_real_escape_string($connection, $_POST['razmer']);
$picurl = mysqli_real_escape_string($connection, $_POST['picurl']);
$query = "
INSERT INTO `banneradd` (
`click`,
`imp`,
`url`,
`razmer`,
`picurl`,
`username`
)
VALUES
(
'$click',
'$imp',
'$url',
'$razmer',
'$picurl',
''
);
";
// Format your query nicely on multiple lines. MySQL will tell you what line
// the error occurred on, but it's not helpful if everything's on the same line.
$result = mysqli_query($connection, $query);
$error = mysqli_error($connection);
if ($error) {
echo "A MySQL error occurred: $error<br>";
echo "<pre>$query</pre>";
// If an error occurred, print the error and the original query
// so you can have a good look at it.
die;
// Stop executing the PHP.
}
echo '<div class="hr">The Banner has been added, please go back to the index: Index </div>';
}
?>
See if that helps. Chances are, the MySQL error will be helpful with diagnosing the problem. You might have just misspelled a column name or table name.