SELECT does not selects [duplicate] - php

This question already has answers here:
Call to undefined method mysqli_stmt::get_result
(10 answers)
Closed 8 years ago.
I'm tryign to creat user_login system for my website. And now i got problems with selection of user_info from database , using mysqli and prepared statements .
My problem is , that i can't get any output . But i'm using the manual at php.net .
Here is what i have got the moment:
<?php
require_once 'php/includes/constants.php';
$connection = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME)or die("Error");
$phone = "0661488342";
$password = "1234";
$query = " SELECT *
FROM userinfo
WHERE phone = ? AND password = ?
LIMIT 1";
$stmt = $connection->prepare($query);
$stmt->bind_param('ss', $phone, $password);
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
echo "Password = ".$row['password'];
The error :
Call to undefined method mysqli_stmt::get_result() in Z:...
Can you advise me something about this ?
Edition 1
PHP version is 5.2.12.(sorry, i forgot this)
But the question remains the same . How can i get the user_info ?

You need to have PHP 5.3.0 and also this method requires the mysqlnd driver. Othervise you will get this error:
Call to undefined method mysqli_stmt::get_result()
Which is what appears to be happening to you.

What is your PHP version, and mysql version?
You should learn more about MySQLi here: http://www.php.net/manual/en/book.mysqli.php

You have an error in your SQL, which you can detect by checking for errors (in this case it outputs them but there are better ways to handle errors.
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!($res = $stmt->get_result())) {
echo "Getting result set failed: (" . $stmt->errno . ") " . $stmt->error;
}
$row = $result->fetch_row()
In your case password column name is a reserved word in MySQl (there is a PASSWORD function). Your SQL should backtick column names and table names:
$query = " SELECT *
FROM `userinfo`
WHERE `phone` = ? AND `password` = ?
LIMIT 1";
FINALLY, it looks like you are stroing passwords in the clear which means you are doing it wrong. See PHP The Right Way: Password Hashing

Related

Updating to Prepared mysqli SELECT statement - it does not find the row

I was advised to update my code to prevent sql injections. So here is what I have.
VARIABLE FROM URL
$Idarticle = "5-6142-8906-6641";
THIS WORKS - OLD
$sql2 = "SELECT * FROM articles WHERE IDArticle IN ('{$Idarticle}')";
$results2 = $conn->query($sql2);
$row2 = $results2->fetch_assoc();
THIS DOES NOT WORK - NEW
$sql2 = "SELECT * FROM articles WHERE IDArticle IN ( ? )";
if ($stmt = $conn->prepare($sql2)) {
$stmt->bind_param("s", $Idarticle);
$stmt->execute();
$row2 = $stmt->fetch();
}
MY CONNECTION SCRIPT
$conn = new mysqli($servername, $username, $password, $db);
In the second example I get no results(no errors either) verses in the first it finds the correct row. I have read numerous similar questions previously asked and while there may be an answer out there, I did not find it. I also tried some of those answers without any success. I appreciate any help.
UPDATED CODE PER COMMENTS
$sql2 = "SELECT * FROM articles WHERE IDArticle = ?";
if (!$stmt = $conn->prepare($sql2)) {
if (!$stmt->bind_param("s", $Idarticle));
echo "error: " . $stmt->error;
if (!$stmt->execute());
echo "error: " . $stmt->error;
$row2 = $stmt->fetch();
}
Still not finding the record / no errors being reported
MY SOLUTION
Having spent close to two days researching and trying to solve this issue, I decided mysqli was at the heart of the problem. Why I am sure this issue does have a solution with mysqli, I ended up moving to PDO. I resisted doing this initially but after a few hours of study, it is in my opinion, as well as many others, far better. Bottom line it now works flawlessly with very few changes. My recommendation, If you are struggling with mysqli, switch to PDO.
A BIG THANK YOU TO THOSE WHO TRIED TO HELP
BTW: Is there any special reason for using IN?
"SELECT * FROM articles WHERE IDArticle = ?"
This is your problem:
$row2 = $stmt->fetch();
mysqli_stmt::fetch returns boolean true/false on success, and you're trying to use it as an array for row2
You must bind your results first with mysqli_stmt::bind_result, and then fetch
See this creative answer for how to get an associative array from bind_result
Preferably, if you have the MySQL native driver installed, then you can extract this directly with mysqli_stmt::get_result
Also, you're not checking for statement errors.
if ( !$stmt->bind_param("s", $Idarticle) )
echo "error: " . $stmt->error;
if ( !$stmt->execute() )
echo "error: " . $stmt->error;
And you should make sure you're using PHP error reporting.
If $results1/$results2 is not a typo, then the new code is very different, because there must be two independent queries.
$sql2 = "SELECT * FROM articles WHERE IDArticle IN ( ? )";
if ($stmt = $conn->prepare($sql2)) {
$stmt->bind_param("s", $Idarticle);
$stmt->execute();
}
But it's not clear then what was done with $results2 later in the code. row2 might be totally unrelated to
$row2 = $results1->fetch_assoc();

Unable to delete from database using php [duplicate]

This question already has answers here:
delete * from table not working [closed]
(2 answers)
Clear data in MySQL table with PHP? [duplicate]
(7 answers)
Closed 7 years ago.
I am trying to delete entries from a mysql database by using a php file and for some reason it doesn't work. The connection (in "connect.php") works, as I am using the same file for my SELECT statements and those work. I am only having trouble with deleting them. Any ideas what I'm doing wrong?
Thanks in advance!
<?php
include "include/connect.php";
if($link === false){
die("ERROR: Could not connect. " . mysql_connect_error());
}
$word = (isset($_GET['email']) ? $_GET['email'] : null);
$sql = "DELETE * from tbl_sbs WHERE eml='" . word . "'";
$result = mysql_query($sql);
?>
You don't use * or column name for DELETE statement unless in WHERE clause for filtering purpose same as in SELECT statement. It should just be
$sql = "DELETE from tbl_sbs";
DELETE general syntax is
DELETE FROM TABLE_NAME WHERE COLUMN_NAME <comparison_operator> SOME_FILTER_CONDITION
So, in your case it should just be
$sql = "DELETE FROM tbl_sbs WHERE eml='" . $word . "'";
Error reporting would have thrown you an undefined constant word notice; IF that wasn't a typo in '" . word . "'.
The * and having checked for errors, would have thrown you the following:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*
References:
https://dev.mysql.com/doc/refman/5.0/en/delete.html
http://php.net/manual/en/function.error-reporting.php
http://php.net/manual/en/function.mysql-error.php
And you must use the $ before a variable name (word)
$sql = "DELETE from tbl_sbs WHERE eml='" . $word . "'";

take a variable from database manipulate and insert other variable into same data base [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
i'm totally beginner at php .
i try to take the highest index of player in my database add to it 1
and then insert the new player information which the new index .
here is my code :
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$email = $_REQUEST['email'];
$con = mysqli_connect(...);
$asking = "SELECT MAX( playerNumber ) as playNum FROM Users";
$result = mysqli_query($con , $asking);
$row = mysql_fetch_array($result);
$numberOfPlayer = $row['playNum'] + 1;
$sql =
"INSERT INTO Users VALUES ( " . $numberOfPlayer . ", " . $username . "," . $password ."," . $email . " , 0)";
$result2 = mysqli_query($conn, $sql);
echo $result2;
mysqli_close($con);
if i ask the query in phpmyadmin its give me the answear but if i try to do something it print me this eror :
Warning: mysql_fetch_array() expects parameter 1 to be resource, object given in /home/u521040346/public_html/learning.php on line 8
thanks for helping.
You are mixing mysql and mysqli. Use mysqli_fetch_array.
Anyway, you should use prepared statements, your query is vulnerable to SQL injection.

Error "Check the manual that corresponds to your MySQL server version for the right syntax to use near" [duplicate]

This question already has answers here:
PDO bindParam issue [duplicate]
(2 answers)
Closed 8 years ago.
I'm trying to perform a SELECT from my database, but I'm getting an error and I don't understand why. All I can tell is that it seems to be failing at the prepare() statement. Any help would be appreciated.
$sQuery = "SELECT * FROM ? WHERE `email` = ? AND `password` = ?";
$sTypes = "sss";
$aParams = array("user", "john.doe#missing.com", "password");
Above is the query and bind_param values.
function conn($sQuery, $sTypes=null, $aParams=null){
$sMessage = '';
$db = new mysqli('localhost','root','','myvyn') or die('unable to connect!');
if($db->connect_errno){
$message = $db->connect_error;
} else{
$stmt = $db->stmt_init();
if (!($stmt->prepare($sQuery))) {
var_dump("Prepare failed: (" . $stmt->errno . ") " . $stmt->error);
}
if($sTypes&&$aParams){
$bindParams[] = $sTypes;
foreach($aParams as $param){
$bindParams[] = $param;
}
call_user_func_array(array($stmt, 'bind_param'), $bindParams);
}
$stmt->execute();
$oResult = $stmt->get_result();
while($rows = $oResult->fetch_assoc()){
$aRows[] = $rows;
}
$oResult->free();
$db->close();
return $aRows;
}
}
You cannot use parameters for a table name, as per here (my bold):
The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value.
However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement, or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. It's not allowed to compare marker with NULL by ? IS NULL too. In general, parameters are legal only in Data Manipulation Language (DML) statements, and not in Data Definition Language (DDL) statements.
Assuming you control the table name (so SQL injection is impossible), you could use something like:
$sQuery = "SELECT * FROM $tblname WHERE `email` = ? AND `password` = ?";
and then only bind the email address and password.

Moving from MySQL to MySQLi

Could somebody please point me in the right direction. I am in the process of making the transition from MySql to MySqli. Normally I would select from the database using th code below and it would allow me to easily use the column value as a working variable:
$SQLCommand = "SELECT * FROM table WHERE column1 = 'ok'";
$Data = mysql_query($SQLCommand);
$DataRow = mysql_fetch_assoc($Data);
$var1 = $DataRow["column1"];
$var2 = $DataRow["column2"];
$var3 = $DataRow["column3"];
$var4 = $DataRow["column4"];
I have researched how to do the MySql equivalent but I find theres a lot of different way using loops etc. Is there a like for like (for want of a better description) that does the same thing? Thanks in advance.
Instead of going with the flow, i care to suggest a PDO alternative
$db = new PDO($dsn, 'username','password');
//$dsn is the connection string to your database.
//See documentation for examples
//The next two rows are optional, but i personally suggest them to
//ease developing, debugging (the 1st) and fetching results (the 2nd)
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$stmt = $db->prepare("SELECT * FROM table WHERE column1 = :c1");
$stmt->bindValue(':c1', 'ok'); //This example is trivial and not necessary
//but it gains relevance when the bound value
//is a variable
$rows = $stmt->fetchAll(); //if you expect a single row use fetch() instead
//do something with the results
You can read more about PDO here: PDO manual
The biggest PDO advantage is that it's independent of the actual database in use by your application. If, by chance, you want to change database in the future, for example SQLITE or PostgreSQL, the only* change you have to make is your $dsn connection string
[*] True only if you used standard SQL queries and nothing vendor-specific.
A direct conversion would be:
$Data = mysqli_query($connection, $SQLCommand);
$DataRow = mysqli_fetch_assoc($Data);
The difference, other than the i is that mysqli_query requires the connection as an argument (as do most mysqli_* functions).
MySQLi also has an object oriented style:
$Data = $connection->query($SQLCommand); // assuming you created the $connection object
$DataRow = $data->fetch_assoc();
They should be like
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_db");
$SQLCommand = "SELECT * FROM table WHERE column1 = 'ok'";
$Data = $mysqli->query($SQLCommand);
$DataRow = $mysqli->fetch_assoc($Data);
Try this LINK
My suggestion is to use mysqli prepared statement whenever you are using user inputs to prevent SQL injection:
See below code uses object oriented approach and prepared statement
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
!$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))") ||
!$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')")) {
echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
/* Prepared statement, stage 1: prepare */
$stmt = $mysqli->prepare("SELECT id, label FROM test WHERE id = ?");
/* Prepared statement, stage 2: bind and execute */
$id = 1;
//note below "i" is for integer, "s" can be used for string
if (!$stmt->bind_param("i", $id)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));
?>

Categories