I'm working transferring my functions from MySQL to MySQLi standards.
This is my old function for getresult
function getResult($sql) {
$result = mysql_query($sql, $this->conn);
if ($result) {
return $result;
} else {
die("SQL Retrieve Error: " . mysql_error());
}
}
However, I have been following the W3schools on the mysqli_query function. Here's where I'm presently at.
function getResult($connection){
$result = mysqli_query($connection->conn);
if ($result) {
return $result;
} else {
die("SQL Retrieve Error: " . mysqli_error());
}
}
Now, the examples on W3schools are just a bit different from how I want to use mysqli_query. I'm trying to make it be directed at my DB, not some input or constants as per examples on W3S.
Notice: Trying to get property of non-object in C:\xampp\htdocs\cad\func.php on line 92
Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\xampp\htdocs\cad\func.php on line 92
Warning: mysqli_error() expects exactly 1 parameter, 0 given in C:\xampp\htdocs\cad\func.php on line 96
SQL Retrieve Error:
Thank you
Your version won't work for a number of reasons, not the least of which is that you haven't included the query you want to send. Assuming $this->conn is set up properly somehow, try this:
function getResult($sql) {
$result = mysqli_query($this->conn, $sql); //Note parameters reversed here.
if ($result) {
return $result;
} else {
die("SQL Retrieve Error: " . mysql_error());
}
}
From the PHP help files I found these function definitions
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
string mysqli_error ( mysqli $link )
mysqli_query() takes the link and the actual query as mandatory parameters, and mysqli_error takes the link as one as well.
http://php.net/manual/en/mysqli.query.php
http://www.php.net/manual/en/mysqli.error.php
Related
I'm trying to convert mysql to mysqli, but I get some errors
first error:
mysqli_query() expects at least 2 parameters, 1 given in /home/.........../class/class.mysql.php on line 55
public function query($res, $pass_no = 1) {
$q1 = mysqli_query($res, $this->db_link);
if (!$q1) {
$this->sql_error();
if ($pass_no == 1) {
if ($this->output_error == 1) {
echo 'Attempting to reconnect to MySQL...' . "\n";
}
$this->db_close();
$this->db_connect();
$this->query($res, 2);
} else {
if ($this->output_error == 1) {
echo 'Reconnection failed; please check your MySQL server settings!' . "\n";
}
}
} else {
return $q1;
}
}
second error:
mysqli_real_escape_string() expects exactly 2 parameters, 1 given in /home/..../index.php on line 14
global $db ;
$username = mysqli_real_escape_string($_POST['username_login']);
$q ="select * from ".DB_PREFIX."admins where username='".$username."' ".
"and password='".md5( $_POST['password_login'])."'";
// echo $q;
$res =$db->query($q);
if($db->num_rows($res)==1)
{
return true ;
}
return false ;
I don't understand the 2 errors
When you get errors: Please help yourself by reading the manual .
1)
first error : mysqli_query() expects at least 2 parameters, 1 given in /home/.........../class/class.mysql.php on line 55
Your code:
$q1 = mysqli_query($res, $this->db_link);
Should be:
$q1 = mysqli_query($this->db_link, $res);
With the Database connection variable FIRST. This variable is required for almost all mysqli_ functions.
2)
second error : mysqli_real_escape_string() expects exactly 2 parameters, 1 given in /home/..../index.php on line 14
See point 1, above:
mysqli_real_escape_string($connectionVariable, $_POST['username_login']);
3)
$q ="select * from ".DB_PREFIX."admins where username='".$username."' ".
"and password='".md5( $_POST['password_login'])."'";
NO
Do not do this!!! Passwords should be stored using PHPs specialist password_hash function. Please read how to use it, why you should use it, why it should be used, and the benefits of using it and here if you need to use it on older versions of PHP.
Here is a code which give the error.
The code is below.
$search = ("SELECT `patData` FROM `reportData` WHERE id = 2")
or die (mysql_error());
echo mysql_result($search,1);
In this code $search Query is work well.
$search = mysql_query("SELECT `patData` FROM `reportData` WHERE id = 2");
if (!$search) {
die('Could not query:' . mysql_error());
}
echo mysql_result($search, 0);
The problem is that mysql_query() is may be returning a Boolean instead of a result resource. There are two reasons this can happen:
You performed query that returns success/fail instead of a result set.
Your query failed.
Notes :
Don't write code that uses the mysql_* functions. They are deprecated and will eventually be removed from PHP.
Use MySQLi or PDO instead.
Warning: mysql_fetch_array() expects parameter 1 to be resource, string given in C:\xampp\htdocs\test\index.php on line 19
<?php
$con = mysql_connect('localhost');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("schedule", $con);
$sql = "SELECT * FROM classes LIMIT 0,50\n";
mysql_query($sql);
IF (!$sql) {
ECHO 'broken';
};
while($row = mysql_fetch_array($sql, MYSQL_BOTH))
{
echo $row['language'] . " " . $row['level'];
echo "<br />";
}
mysql_close($con);
?>
why? the query works in phpmyadmin
Your parameter to mysql_fetch_array() function is your SQL statement string. This is what your warning say. You should first use
$res = mysql_query($sql);
and pass $res as parameter to mysql_fetch_array()
The input to mysql_fetch_Array is a resource, which is also the returned value from mysql_query. If you pass the value $sql to mysql_query(), it will not modify the parameter since it is passed by value. You have to assign the return value to another variable, which will be the desired resource.
$result = mysql_query($sql);
And then, pass the result parameter to mysql_fetch_array :
$row = mysql_fetch_array($result, MYSQL_BOTH)
Another important note: As you might see in all the related threads, read the red box in the php.net for these functions.
Use of this extension is discouraged. Instead, the MySQLi or PDO_MySQL
extension should be used. See also MySQL: choosing an API guide and
related FAQ for more information. Alternatives to this function
include:
mysqli_query() PDO::query()
Change: mysql_query($sql);
To: $sql = mysql_query($sql);
Cited from PHP.net about mysql_query():
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning
resultset, mysql_query() returns a resource on success, or FALSE on
error.
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc,
mysql_query() returns TRUE on success or FALSE on error.
In your case the resource is returned, but you've forgotten to assign it to anything.
Change mysql_query($sql) to $resource = mysql_query($sql).
Full documentation right here: http://php.net/manual/en/function.mysql-query.php
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given
my code php is :
function getResourceLevel($vid) {
$q = "SELECT * from " . TB_PREFIX . "fdata where vref = $vid";
$result = mysql_query($q, $this->connection);
return mysql_fetch_assoc($result);
}
Please Help me
It looks like mysql_query() has returned false.
This could by due to an error in your mysql syntax or due to a lack of permissions for accessing the database table you have requested.
In either case, you can try calling mysql_error() which will return a string with a best guess of what went wrong with your last mysql function.
Edit: As mentioned in some of the comments, the use of mysql_* functions is discouraged, so if you have opportunity you should update your code to use the mysqli or PDO MySQL extensions. Better yet, use something like Zend DB to move you one layer further away from the database API.
Try to echo your query and run in some mysql query browser and check if its giving required results.
function getResourceLevel($vid) {
$q = "SELECT * from " . TB_PREFIX . "fdata where vref = $vid";
echo $q;
$result = mysql_query($q, $this->connection);
return ($result) ? mysql_fetch_assoc($result) : false;
}
Try this
function getResourceLevel($vid) {
$q = "SELECT * from " . TB_PREFIX . "fdata where vref = $vid";
$result = mysql_query($q, $this->connection) || die(mysql_error());
return mysql_fetch_assoc($result);
}
Notice the || die(mysql_error()) statement.
This will stop the code and show the sql error that is being returned as false.
Hope this helps.
Here is the code in question:
From index.php:
require_once('includes/DbConnector.php');
// Create an object (instance) of the DbConnector
$connector = new DbConnector();
// Execute the query to retrieve articles
$query1 = "SELECT id, title FROM articles ORDER BY id DESC LIMIT 0,5";
$result = $connector->query($query1);
echo "vardump1:";
var_dump($result);
echo "\n";
/*(!line 17!)*/ echo "Number of rows in the result of the query:".mysql_num_rows($result)."\n";
// Get an array containing the results.
// Loop for each item in that array
while ($row = $connector->fetchArray($result)){
echo '<p> <a href="viewArticle.php?id='.$row['id'].'">';
echo $row['title'];
echo '</a> </p>';
From dbconnector.php:
$settings = SystemComponent::getSettings();
// Get the main settings from the array we just loaded
$host = $settings['dbhost'];
$db = $settings['dbname'];
$user = $settings['dbusername'];
$pass = $settings['dbpassword'];
// Connect to the database
$this->link = mysql_connect($host, $user, $pass);
mysql_select_db($db);
register_shutdown_function(array(&$this, 'close'));
} //end constructor
//*** Function: query, Purpose: Execute a database query ***
function query($query) {
echo "Query Statement: ".$query."\n";
$this->theQuery = $query;
return mysql_query($query, $this->link) or die(mysql_error());
}
//*** Function: fetchArray, Purpose: Get array of query results ***
function fetchArray($result) {
echo "<|";
var_dump($result);
echo "|> \n";
/*(!line 50!)*/$res= mysql_fetch_array($result) or die(mysql_error());
echo $res['id']."-".$res['title']."-".$res['imagelink']."-".$res['text'];
return $res;
}
Output:
Query Statement: SELECT id, title FROM articles ORDER BY id DESC LIMIT 0,5 vardump1:bool(true)
PHP Error Message
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /*path to*/index.php on line 17
Number of rows in the result of the query: <|bool(true) |>
PHP Error Message
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /*path to*/DbConnector.php on line 50
Your problem is in fallowing line:
return mysql_query($query, $this->link) or die(mysql_error())
it should have been written like this:
$result = mysql_query($query, $this->link);
if(!$result) die(mysql_error());
return $result;
It is common in dynamic languages that or returns first object which evaluates to true, but in PHP the result of X or Y is always true or false.
As you can learn from the manual, mysql_query return value type is not boolean but resource.
Something in your code converting it
Agree with above, you have an issue with your mysql_query. It should never return True. Either false or a resource.
Refactor : mysql_query($query, $this->link) or die(mysql_error())
echo mysqlerror() after your query and see what the error message is. You probably do not have a valid connection.