PHP an MySQL - Fatal error: Function name must be a string - php

I'm trying to show a value from a database table through PHP echo. The MySQL result is a double (10, 2).
<?php $link = new mysqli('127.0.0.1', '*******', '*******', '*******');
if ($link->connect_errno) {
die('Failed to connect to MySQL: (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
$user = $_SESSION['user'];
$result = $link->query("SELECT * FROM users WHERE username='$user' AND active=1");
$numrows = $result->num_rows;
if($numrows == 0 || $numrows > 1)
{
$link->close();
session_destroy();
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=**************">';
exit;
}
else if($numrows == 1)
{
//$sid = $result(8);
echo '<strong>this is my string in which i want to show the result in' . $result(8) . 'rest of the string';}?>
Line where the error is show is the echo line (in the end). Can anyone point me out to what I am doing wrong here? Thank you.

you are calling $result(8) which is a method call in php. I think you meant
$dataRow = $result->fetch_array(MYSQLI_ASSOC);
// collect whatever you need from the array $dataRow array
since PHP is an interpreted language you can do such things as assign a value to a variable and call that variable
$func = 'myFunc';
$func(); // will call the function myFunc

The $result variable is a MySQLi Result. You want to get a row from that result set. To do that, use fetch_assoc. This will give you an associative array with all of the fields of the table as keys.
$row = $result->fetch_assoc();
echo $row['username'];
echo $row['whatever'];
EDIT: It may be valuable to note that you are susceptible to the following security risks: SQL injection, cross-site scripting, and Cookie tampering.

You are trying to access to an array value, you must use:
$result[8] and not $result(8)
Best regards!

Look at this - $result(8) (last row). A variable can't have arguments. You probably wanted $result[8] (9th element in array).

Related

How do I access the index of mysql_fetch_array from database in php?

I know how to fetch data using mysql_fetch_array and one variable will hold the data, but after fetching the data I want to access and print my desired index from the fetched data.
My current code:
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("htmlcontent", $con);
$s = mysql_query("SELECT * FROM tags WHERE place = 'luzon'");
while($roww = mysql_fetch_assoc($s))
{
$pt2 = $roww['url'];
echo "$pt2" ."<br>";
}
?>
Your code would print the value held by the url field in your tags table.
You do not have to put $pt2 within quotes, just use echo $pt2 . "<br>";
Also, I would recommend you use PDO or mysqli to make it work.
You may use mysql_fetch_array instead, (if you need array indexes too).
PS. I highly recommend you use PDO or mysqli instead of mysql.

Google SQL PHP No Data Showing - Connected

I am struggling to view some data via PHP. I have a SQL database with Google. I am struggling to extract the data and desperately need some help!
The PHP keeps saying there is 0 records, even though there is a number of records within the 'timing' database and 'events' table.
If anyone has any ideas why this is not working I would be very grateful!
<?php
$link = new mysqli('IP_ADDRESS:3306','root','PASSWORD',timing);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully ';
$sql = "SELECT event_id FROM events";
$result = $link->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>Event ID</th><th>Event Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["event_id"];
}
echo "</table>";
}
else {
echo "0 results";
}
mysql_close($link);
?> 
Ok i think i got it. From PHP.net:
OO syntax only: If a connection fails an object is still returned. To check if the connection failed then use either the mysqli_connect_error() function or the mysqli->connect_error property as in the preceding examples.
This means $link in your code will always be a MySQLi resource, and that it will always cast to true. What you need to do is to check your resource object for errors properly, like this:
if ($link->connect_error)
die('Connect Error: ' . $link->connect_error);
Unless timing is a defined constant, and it looks like that is not the case, being that a string you should wrap it in quotes or double-quotes. A non-defined constant should cast to a string in any case, but since i can't see any other error in your code that might be what is causing your issue. Try changing
$link = new mysqli('IP_ADDRESS:3306','root','PASSWORD',timing);
to
$link = new mysqli('IP_ADDRESS:3306', 'root', 'PASSWORD', 'timing');

Retrieving row from MySQL Database via PHP

Please bear with me, I'm new here - and I'm just starting out with PHP. To be honest, this is my first project, so please be merciful. :)
$row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."' LIMIT 1"));
echo $row['message'];
Would this be enough to fetch the message from the database based upon a pre-defined '$code' variable? I have already successfully connected to the database.
This block of code seems to return nothing - just a blank space. :(
I would be grateful of any suggestions and help. :)
UPDATE:
Code now reads:
<?php
error_reporting(E_ALL);
// Start MySQL Connection
REMOVED FOR SECURITY
// Check if code exists
if(mysql_num_rows(mysql_query("SELECT code FROM data WHERE code = '$code'"))){
echo 'Hooray, that works!';
$row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."' LIMIT 1")) or die(mysql_error());
echo $row['message'];
}
else {
echo 'That code could not be found. Please try again!';
}
mysql_close();
?>
It's best not to chain functions together like this since if the query fails the fetch will also appear to fail and cause an error message that may not actually indicate what the real problem was.
Also, don't wrap quotes around integer values in your SQL queries.
if(! $rs = mysql_query("SELECT message FROM data WHERE code = ". (int) $code ." LIMIT 1") ) {
die('query failed! ' . mysql_error());
}
$row = mysql_fetch_array($rs);
echo $row['message'];
And the standard "don't use mysql_* functions because deprecated blah blah blah"...
If you're still getting a blank response you might want to check that you're not getting 0 rows returned. Further testing would also include echoing out the query to see if it's formed properly, and running it yourself to see if it's returning the correct data.
Some comments:
Don't use mysql_*. It's deprecated. use either mysqli_* functions or the PDO Library
Whenever you enter a value into a query (here, $code), use either mysqli_real_escape_string or PDO's quote function to prevent SQL injection
Always check for errors.
Example using PDO:
//connect to database
$user = 'dbuser'; //mysql user name
$pass = 'dbpass'; //mysql password
$db = 'dbname'; //name of mysql database
$dsn = 'mysql:host=localhost;dbname='.$db;
try {
$con = new PDO($dsn, $user, $pass);
} catch (PDOException $e) {
echo 'Could not connect to database: ' . $e->getMessage();
die();
}
//escape code to prevent SQL injection
$code = $con->quote($code);
//prepare the SQL string
$sql = 'SELECT message FROM data WHERE code='.$code.' LIMIT 1';
//do the sql query
$res = $con->query($sql);
if(!$res) {
echo "something wrong with the query!";
echo $sql; //for development only; don't output SQL in live server!
die();
}
//get result
$row = $res->fetch(PDO::FETCH_ASSOC);
//output result
print_r($row);

MySQL error when getting variable from URL

This is the code I have, but I get this error when I try to get variable from the url: Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource
The URL variable DEVID is a long string of characters, numbers, dashes, and underscores. Any ideas on what is wrong?
<?php
$con = mysql_connect("server","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
$result = mysql_query("SELECT * FROM $user WHERE DEVID=$DEVID");
while($row = mysql_fetch_array($result))
{
if (($row["FN"]) == NULL){
echo '<meta http-equiv="refresh" content="1;url=../register/default.php?user=';
echo $_GET["user"];
echo '&DEVID=';
echo $_GET["DEVID"];
echo '">Please hold, we are taking you to the registration page.<br/><br/>';
}
}
mysql_close($con);
?>
If $DEVID is a VARCHAR field then you'll need single quotes around it in your SQL query:
SELECT * FROM $user WHERE DEVID='$DEVID'
Where is $DEVID being set before the query? You're not using PHP register_globals, and that's coming from a query-string variable are you? This is 2012! When are people going to stop using that?
Do the variables $user and $DEVID has values? Have they been initialized ?
Assuming that $user and $DEVID has been initailized the error is happening because mysql_query is returning false as the SQL query generates error when executed.
Moreover you should not use variables directly obtained from the URL. Clean the value for possible presence of single qoutes. Use mysql_real_esacape_string(). Replace the mysql_query line with the below to see the SQL error if it occurs.
$DEVID=mysql_real_escape_string($DEVID);
$result = mysql_query("SELECT * FROM $user WHERE DEVID='$DEVID'") or die(mysql_error());

Posting variable returns invalid

I am using a simple PHP script for the activation part of one of my applications. The applications posts one variable to the page (http://validate.zbrowntechnology.info/WebLock.php?method=validate). The variable is the serial number, posted as 'Serial'. Each time I post to this page, it returns Invalid. Here is the code:
<?php
$serial = $_POST['Serial'];
$method = $_GET['method'];
$con = mysql_connect("HOSTHERE", "USERHERE", "PASSHERE");
if(!$con) {
die('Unable to connect to MySQL: ' . mysql_error());
}
if($method == "validate") {
mysql_select_db("zach_WebLock", $con);
$query = "SELECT Key, Status FROM Validation WHERE Key='".mysql_real_escape_string($serial)."'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0) {
echo "Valid";
} else {
echo "Invalid";
}
} else {
echo "Unkown Method";
}
?>
Here Is The Error From PHP,
PHP Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given
Right after the query use mysql_error() to see what happened. And Key is a bad choice for a column name because it's a reserved word in SQL. You can enclose it in `` to tell MySQL it's an identifier. Do some more debugging like this:
...
if (!mysql_select_db("zach_WebLock", $con)) die('mysql_select_db failed');
$query = "SELECT `Key`, Status FROM Validation WHERE `Key`='".mysql_real_escape_string($serial)."'";
print "query=$query<br>\n";
$result = mysql_query($query, $con);
print "error=" . mysql_error($con);
...
You're missing a closing parenthesis on this line:
if(mysql_num_rows($result) > 0 {
Is that missing in your code or just your question?
You may also want to add
if (!$result) {
print mysql_error();
}
after your query
Try Like This
$query = "SELECT Key, Status FROM Validation WHERE Key='".$serial."'";
What happens if at the last line you add this?
else echo 'Unknown method';
What may be happening is that $_POST and $_GET are not getting populated, this is a setting in php.ini, if I remember correctly (search for "superglobals" in the php docs).
edit: also, you have a very bad security risk there, google "sql injection". Basically the problem is that you could get any SQL directly into your database, and if the php user has enough permissions it could mean that anyone can, for example, delete all the data from your Validation table. You should at least do something like this:
$query = "SELECT Key, Status FROM Validation WHERE Key='".addslashes($serial)."'";
It could be a typo but you are missing a closing parenthesis here:
if(mysql_num_rows($result) > 0 {
^
And you might have turned off you error reporting, in which case you get a blank page.
Try echoing $serial:
echo $serial;
And is it what you typed in form?

Categories