My following piece of code works fine on chrome, however when I try to load it on firefox is says: 'Notice: Trying to get property of non-object in */loginTrueFunctions.php on line 23'
these are the "problem codes":
$firstName = $sqlObjectFirstName->firstName;
And:
$lastName = $sqlObjectLastName->lastName;
PHP code:
function getFullName($id, $mysqli_connect){
if(isset($_SESSION['login'])){
$queryFirstName = mysqli_query($mysqli_connect,"
SELECT firstName
FROM users
WHERE id = '$id'
LIMIT 1
");
$sqlObjectFirstName = mysqli_fetch_object($queryFirstName);
$firstName = $sqlObjectFirstName->firstName;
printf( ucfirst($firstName));
printf(' ');
$queryLastName = mysqli_query($mysqli_connect,"
SELECT lastName
FROM users
WHERE id = '$id'
LIMIT 1
");
$sqlObjectLastName = mysqli_fetch_object($queryLastName);
$lastName = $sqlObjectLastName->lastName;
printf( ucfirst($lastName));
}
}
Thanks in advance!
EDIT: if I call the result as an array, firefox gives no error nor a result, but then chrome gives this error: Cannot use object of type stdClass as array.
Then I change mysqli_fetch_object to mysqli_fetch_array, result: Chrome works fine, firefox doesn't give an error nor a result.
Probably your session (or cookie) contents are different between your browsers(for example, you are logged in with one, but not with the other). Do a
var_dump($_SESSION); var_dump($_COOKIE);
and see
Check the return value of mysqli_fetch_object($queryFirstName); before trying to access it. It's likely your query is not returning anything.
Another thing to mention is DO NOT EVER PASS USER DATA DIRECTLY INTO A QUERY as you are vulnerable to a sql injection attack. Just because you are using mysqli, doesn't make you immune. You have to use the features of mysqli such as prepared statements to avoid sql injection.
More likely then not the error appears on both browsers and there is just broken markup and they are fixing it in two different ways, one leaving your markup visible the other not. Without seeing code there is no way to know for sure.
PROTIP
You can select multiple fields from a database in a single call.
$res = mysqli_query($mysqli_connect,"
SELECT firstName, lastName
FROM users
WHERE id = '".(int)$id."'
LIMIT 1");
if (!$res) die("Error running query at ".__FILE__." : ".__LINE__);
$person = mysqli_fetch_object($res);
echo $person->firstName;
echo $person->lastName;
Post the code that is posting this data from the browser to the php script, it very well could be that the data you are submitting to the server is different because of the browsers.
also, where is the code that shows how your data is being called on the php side of things?
Related
Using a plugin I'm able to use PHP on page by using [insert_php] as a tag however, whenever I try using SQL it doesn't seem to work.
I tried using:
global $wpdb;
$prepared = $wpdb->get_row(
"SELECT SiteID, SiteName
FROM $wpdb->Site
WHERE SiteID = 1");
echo $prepared->SiteName;
echo "test";
All I'm getting is test on the page and I've tested to see if my sql statement was at fault and it seems to be working fine so I'm guessing there's an issue with $wpdb or the way I'm outputting the data.
WordPress.org has a lot of detailed information in their reference.
I think attempting to refer to $wpdb->Site is a likely suspect for why your code is not working. You will need to know the exact fields in the table to pull your information.
Here is a reference for the wp_site table. I think you're actually looking for the 'domain' field, not 'sitename'.
Try replacing $wpdb->Site with the actual name of the table. I also get errors like that at first since $wpdb->table_name only works with the default wp tables.
EDIT
It should be something like this:
SELECT SiteID, SiteName FROM Site WHERE SiteID = 1
I am trying to register a button click on my website using PHP.The click downloads a file to client's machine. Database connection was tested before and it works fine. I just need to register that click into DB. Here is my code, could you guide me through?
echo '<div id="fdbox1"><h2>Details</h2><p> Download full details in PDF format ('.$file_size.')</p></div>';
if(isset($_GET['dl']))
{
$server = "xx.xxx.xx.xxx";
$dbusername = "xxxx";
$dbpassword = "xxxx";
$database = "xxxx";
$dbcon = new mysqli($server,$dbusername,$dbpassword, $database);
$userid = $_SESSION['suserid'];
$date_downloaded = date('Y-m-d H:i:s');
$sql = "INSERT INTO external_activity (
userid,
saleid,
activity,
date_register,
) VALUES (
'".$userid."',
'".$ref_no."',
'".'Downloaded file'."',
'".$date_downloaded."'
)";
$dbcon->query($sql);
$dbcon->close();
}
If using jquery is an option, you could create a "register_click.php", paste the if(isset($_GET['dl'])) stuff inside and call it via ajax using an onclick listener that you will have to create and bind to the anchor.
You could do it with POST data instead of GET.
$i = 0;
if $_POST['submit'] {
$i++;
$number_of_times_clicked = $number_of_times_clicked_stored_into_database + $i;
}
After that restore the new value back into the database. If you really want the onclick you need javascript. PHP is unable to check when a button is clicked, since the code only works once when the page is loaded.
This is too long for a comment.
The & in your code might give you some problems, I said "might". If so, then consider changing those to & (ampersands).
Should it be the case, then you could change:
echo '<div id="fdbox1"><h2>Details</h2><p> Download full details in PDF format ('.$file_size.')</p></div>';
to:
echo '<div id="fdbox1"><h2>Details</h2><p> Download full details in PDF format ('.$file_size.')</p></div>';
Then you will need to check and see if each GET array is is set/not empty with isset() and !empty().
References:
http://php.net/manual/en/function.isset.php
http://php.net/manual/en/function.empty.php
I only see if(isset($_GET['dl'])) as a single array, so it's unsure as to how you're wanting to fetch the other GET arrays in your URL and if you did set those.
Your present code (if it's the full code), will throw a few notices about certain variables not being defined.
For example, the if(isset($_GET['dl'])) and using the other GET arrays, would look like this:
if( isset($_GET['f']) && !empty($_GET['l']) && !empty($_GET['dl']) ){
// do something inside here
}
You also need to make sure that the session was indeed started with session_start(); and to be included inside all files using sessions.
Reference:
http://php.net/manual/en/function.session-start.php
This is usually the first line under the opening PHP tag.
<?php
session_start();
// rest of your code
The $userid = $_SESSION['suserid']; needs to have a value/equal something, so that is unknown as to whether or not there is indeed a value for it.
Error reporting will be of help here for you, as will checking for errors against your query.
References:
http://php.net/manual/en/function.error-reporting.php
http://php.net/manual/en/mysqli.error.php
You also have a trailing comma in date_register, < and that needs to be removed, as I already stated in comments.
That alone would have thrown a syntax error.
The use of '".'Downloaded file'."' is unclear. If you just want to insert the Downloaded file as a string, then you can just place it inside single quotes 'Downloaded file' and do:
$sql = "INSERT INTO external_activity (
userid,
saleid,
activity,
date_register
) VALUES (
'".$userid."',
'".$ref_no."',
'Downloaded file',
'".$date_downloaded."'
)";
Make sure that the date_register column type is DATE and not VARCHAR or other format. Although VARCHAR would not throw an error, it's best to use MySQL's built-in dating functions; that column's type is unknown.
Now, make sure that the userid column is not an AUTO_INCREMENT'ed column, otherwise your code will fail.
If the ultimate goal here is to "UPDATE" that userid column, then use just that, UPDATE:
http://dev.mysql.com/doc/refman/5.7/en/update.html
You also need to make sure that all columns' types are correct and have a length long enough to accomodate the incoming data and that there are no characters that MySQL will complain about, such as apostrophes.
Escaping those with a prepared statement will ensure that it doesn't throw/cause a syntax error and is something you should be using in order to help prevent against an SQL injection and you are open to one right now.
References:
https://en.wikipedia.org/wiki/Prepared_statement
https://en.wikipedia.org/wiki/SQL_injection
This is the best way that I can offer for the question, given the information left in the question.
Again; check for errors. That is one of the most important things that needs to be done during the development of your code.
Lets say I have a file called comments.php. In it I have a row like this:
$post_id = $_GET['id'];
$result = mysqli_query($con,"SELECT * FROM comments WHERE post_id = $post_id");
$post_id is the id of the actual entry.
If I echo $post_id it shows the entry's number, no problem there.
There's also a file called comment_send.php.
In it I want to send a comment, alongside with the id of the actual entry, so the comments will know where they belong to.
$post_id = $_GET['id'];
$result = mysqli_query($con,"SELECT * FROM comments WHERE post_id = $post_id");
$sql="INSERT INTO comments (comment, post_id) VALUES ('$_GET[comment]','$post_id')";
However, when I hit the submit button I get this: Notice: Undefined index: id
I dont understand the problem because in the comments.php everything works fine but if I move the same part into another file it fails. Does anyone know what my problem might be?
And yeah, the comment arrives in the database, with the number 0, instead of the entry number.
Your submitting data from the client to the server using a form, right? Check your action on your form. Is it POST (as it should be if you are updating your database)? If so, change $post_id = $_GET['id']; to $post_id = $_POST['id'];
As a troubleshooting tool, I typically add something like echo('<pre>'.print_r($_REQUEST,1).'</pre>'); to the top of my page. You can then find out what type of data you are sending to the server. Then when you get to your SQL statement, be sure to echo the query to see what it is.
Also, sanitize your data as you are open to SQL injection.
It doesn't look like you are passing 'id' to your comment_send.php page. Either pass it in with your comment, or save it as a $_SESSION variable on the previous page.
I'm experiencing a strange problem. I'm caching the output of a query using memcache functions in a file named count.php. This file is called by an ajax every second when a user is viewing a particular page. The output is cached for 5 seconds, so within this time if there will be 5 hits to this file i expect the cached result to be returned 3-4 times atleast. However this is not happening, instead everytime a query is going to db as evidenced from a echo statement, but if the file is called from the browser directly by typing the url (like http://example.com/help/count.php) repeatedly many times within 5 seconds data is returned from cache (again evidenced from the echo statement). Below is the relevant code of count.php
mysql_connect(c_dbhost, c_dbuname, c_dbpsw) or die(mysql_error());
mysql_select_db(c_dbname) or die("Coud Not Find Database");
$product_id=$_POST['product_id'];
echo func_total_bids_count($product_id);
function func_total_bids_count($product_id)
{
$qry="select count(*) as bid_count from tbl_userbid where userbid_auction_id=".$product_id;
$row_count=func_row_count_only($qry);
return $row_count["bid_count"];
}
function func_row_count_only($qry)
{
if($_SERVER["HTTP_HOST"]!="localhost")
{
$o_cache = new Memcache;
$o_cache->connect('localhost', 11211) or die ("Could not connect to memcache");
//$key="total_bids" . md5($product_id);
$key = "KEY" . md5($qry);
$result = $o_cache->get($key);
if (!$result)
{
$qry_result = mysql_query($qry);
while($row=mysql_fetch_array($qry_result))
{
$row_count = $row;
$result = $row;
$o_cache->set($key, $result, 0, 5);
}
echo "From DB <br/>";
}
else
{
echo "From Cache <br/>";
}
$o_cache->close();
return $row_count;
}
}
I'm confused as to why when an ajax calls this file, DB is hit every second, but when the URL is typed in the browser cached data is returned. To try the URL method i just replaced $product_id with a valid number (Eg: $product_id=426 in my case). I'm not understanding whats wrong here as i expect data to be returned from cache within 5 seconds after the 1st hit. I want the data to be returned from cache. Can some one please help me understand whats happening ?
If you're using the address bar, you're doing a GET, but your code is looking for $_POST['...'], so you will end up with an invalid query. So for a start, the results using the address bar won't be what you're expecting. Is your Ajax call actually doing a POST?
Please also note that you've got a SQL injection vulnerability there. Make sure $product_id is an integer.
There are many problems with your code, first of all you always connect to the database and select a table, even if you don't need it. Second, you should check $result with !empty($result) which is more reliable as just !$result, because it's also covers empty objects.
As above noted, if the 'product_id' is not in the $_POST array, you could use $_REQUEST to also cover $_GET (but you shouldn't, if you are certain it's coming via $_POST).
I am writing a simple user/login system in Php with postgresql.
I have a function that confirms whether username/passwords exists, which gets activated when a user presses the Login button.
public function confirmUserPass($username, $password){
$username=pg_escape_string($username);
/* Verify that user is in database */
$q = "SELECT password FROM users WHERE email = '$username'";
$result = pg_query($this->link,$q);
/* Do more operations */
}
I want to print the query stored in $results such that I can see it on the browser. When I do it in phppgAdmin using SQL it shows me the output but I cannot see it on the browser. I tried echo and printf but I could not see anything on the browser. I also tried to see view source from the browser but it shows nothing.
Can somebody help me with that?
Regards
From your code: $result = pg_query($this->link,$q);
As you've found already, trying to display the contents of $result from the line above will not give you anything useful. This is because it doesn't contain the data returned by the query; it simply contains a "resource handle".
In order to get the actual data, you have to call a second function after pg_query(). The function you need is pg_fetch_array().
pg_fetch_array() takes the resource handle that you're given in $result, and asks it for its the next set of data.
A SQL query can return multiple results, and so it is typical to put pg_fetch_array() into a loop and keep calling it until it returns false instead of a data array. However, in a case like yours where you are certain that it will return only one result, it is okay to simply call it once immediately after pg_query() without using a loop.
Your code could look like this:
$result = pg_query($this->link,$q);
$data = pg_fetch_array($result, NULL, PGSQL_ASSOC);
Once you have $data, then you've got the actual data from the DB.
In order to view the individual fields in $data, you need to look at its array elements. It should have an array element named for each field in the query. In your case, your query only contains one field, so it would be called $data['password']. If you have more fields in the query, you can access them in a similar way.
So your next line of code might be something like this:
echo "Password from DB was: ".$data['password'];
If you want to see the raw data, you can display it to the browser using the print_r() or var_dump() functions. These functions are really useful for testing and debugging. (hint: Wrap these calls in <pre> tags in order for them to show up nicely in the browser)
Hope that helps.
[EDIT: an after-thought]
By the way, slightly off-topic, but I would like to point out that your code indicates that your system may not be completely secure (even though you are correctly escaping the query arguments).
A truly secure system would never fetch the password from the database. Once a password has been stored, it should only be used in the WHERE clause when logging in, not fetched in the query.
A typical query would look like this:
SELECT count(*) n FROM users WHERE email = '$username' AND password = '$hashedpass'
In this case, the password would be stored in the DB as a hashed value rather than plain text, and the WHERE clause would compare that against a hashed version of the password that has been entered by the user.
The idea is that this allows us to avoid having passwords accessible as plain text anywhere in the system, which reduces the risk of hacking, even if someone does manage to get access to the database.
It's not foolproof of course, and it's certainly not the whole story when it comes to this kind of security, but it would definitely be better than the way you seem to have it now.
You must connect to database , execute query, and then fetch results.
try this example from php.net
<?php
public function confirmUserPass($username, $password){
$username=pg_escape_string($username);
// Connecting, selecting database
$dbconn = pg_connect("host=localhost dbname=publishing user=www password=foo")
or die('Could not connect: ' . pg_last_error());
// Performing SQL query
$query = "SELECT password FROM users WHERE email = '$username'";
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
// Printing results in HTML
echo "<table>\n";
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Free resultset
pg_free_result($result);
// Closing connection
pg_close($dbconn);
?>
}
?>
http://php.net/manual/en/book.pgsql.php