How to fetch data in PHP with MySQLi? - php

I tried several times but cannot succeed in getting the right syntax—according to PHP 5.5.12 —to fetch single or multiple rows from my database.
session_start();
$con=mysqli_connect("localhost","root","","doortolearn");
if (!$con) {
echo "Could not connect to DBMS";
}
$query="select * from teacher where tremail='$_POST[email]' and trpasssword='$_POST[password]'";
$result=mysqli_query($con,$query);
$flag=FALSE;
while ($row=mysqli_fetch_array($result,MYSQLI_BOTH)) {
$_SESSION['email']=$row['email'];
$flag=TRUE;
}

First, you have no single quotes ' around $_POST[password]:
$query = "SELECT * FROM teacher WHERE tremail='". $_POST['email'] ."' and trpasssword='" . $_POST['password'] . "'";
$result = mysqli_query($con, $query) or die(mysqli_error($con));
$flag = FALSE;
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$_SESSION['email'] = $row['email'];
$flag = TRUE;
}
But past that, do you even have a MySQL database connection set here? I see $con but is that really working?
Also, check if there are errors by adding or die(mysql_error($con)) to your mysqli_query($con, $query) line.
Also, you have a $_SESSION value, but do you even set session_start at the beginning of your script?
But I also recommend you use mysqli_stmt_bind_param for your values to at least escape them if you are not going to do basic validation:
$query = "SELECT * FROM teacher WHERE tremail=? and trpasssword=?";
mysqli_stmt_bind_param($query, 'ss', $_POST['email'], $_POST['password']);
$result = mysqli_query($con, $query) or die(mysqli_error($con));
$flag = FALSE;
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$_SESSION['email'] = $row['email'];
$flag = TRUE;
}

To successfully fetch data from MySQL using mysqli extension in PHP you need to perform more or less three actions: connect, execute prepared statement, fetch data.
Connection:
The connection is really simple. There should always be only 3 lines of code for opening a connection. You enable error reporting, create new instance of mysqli, and set the correct charset.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'user', 'pass', 'db_name');
$mysqli->set_charset('utf8mb4');
Prepared statement
This is the tricky part. You need to prepare SQL statement to be executed. Careful, never concatenate PHP variables into SQL directly. Bind the variables using placeholders. Once the statement is ready you can execute it on the server.
$stmt = $mysqli->prepare('SELECT * FROM teacher WHERE tremail=?');
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
Fetch the data
If your prepared statement should return some results, you need to fetch them and do something with the records. To fetch the result use get_result(). This will give you an object that you can iterate on to fetch each row one by one.
$result = $stmt->get_result();
foreach ($result as $row) {
echo $row['user_id'];
}
If you are only starting learning PHP, please consider learning PDO instead. It is easier to use and offers more functionality. Use mysqli only for legacy projects.

can You try this code
<?php $query=mysqli_query($connection, "SELECT * FROM user");
while($rows=mysqli_fetch_array($query)){ ?>
<tr>
<td><?php echo $rows['name']; ?></td>
<td><?php echo $rows['age']; ?></td>
<td><?php echo $rows['mobile']; ?></td>
<td><?php echo $rows['email']; ?></td>
</tr>
<?php } ?>

$r =$mysqli->query("select * from users");
while ( $row = $r->fetch_assoc() )
{
?>
<tr>
<td><?php echo $i++; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['pwd']; ?></td>
</tr>
<?php
}
?>

Related

Ain't echo when row doesn't exist in PHP

<tr>
<td id="idtypesectype2">Skype</td>
<td id="doubledotsec">:</td>
<td>
<?php
$search = $_GET['search'];
$sql ="SELECT * FROM contact_info WHERE CU_id='$search' AND contact_information_type='social_media_skype' AND visibility='1'";
$result = $db -> query($sql);
WHILE ($row=$result->fetch_assoc()) {
if(mysqli_num_rows($result) < 0) {
echo "-";
} else {
echo $row['contact_information'];
}
?><br>
<?php
}
?>
</td>
</tr>
I don't get - when the row is empty, instead it is a blank. Can you help me with this isuue? I want that it will show - when the row doesn't exist.
You're checking how many rows your query returns in your while loop, where you fetch the single rows. Yet, if there are none, you never get in the while loop.
So, what you need to do, is put your if condition before the while, and the while loop inside the else statement.
First, you have to remember that a while loop with nothing to process just terminates and continues with the code after it. So if you want to test the number of rows in the resultset, you need to do it before running the while loop
You also need to use prepared queries to protect yourself from SQL Injection Attack
<tr>
<td id="idtypesectype2">Skype</td>
<td id="doubledotsec">:</td>
<td>
<?php
$sql ="SELECT *
FROM contact_info
WHERE CU_id=?
AND contact_information_type='social_media_skype'
AND visibility='1'";
# prepare and bind parameter to the query to protect against SQL Injection
$stmt = $db->prepare($sql);
$stmt->bind_param('i', $_GET['search']);
$stmt->execute();
$results = $stmt->get_result();
if($result->num_rows == 0) {
echo "-";
}
while ($row=$result->fetch_assoc()) {
echo $row['contact_information'];
}
?>
<br>
</td>
</tr>
I think you must change your code to this to get the disired result:
<tr>
<td id="idtypesectype2">Skype</td>
<td id="doubledotsec">:</td>
<td>
<?php
$search = $_GET['search'];
$sql ="SELECT * FROM contact_info WHERE CU_id='$search' AND contact_information_type='social_media_skype' AND visibility='1'";
$result = $db -> query($sql);
if($result->num_rows < 0) {
echo "-";
} else {
WHILE ($row=$result->fetch_assoc()) {
echo $row['contact_information'];
}
?><br>
<?php
}
?>
</td>
</tr>

Query with data from user in MSSQL with PHP [duplicate]

This question already has answers here:
sqlsrv_num_rows Not Returning Any Value
(2 answers)
Closed 2 years ago.
(I'm forced to work on microsoft sql server in my internship).
I don't understand why my query doesn't work in PHP (it returns no data), but it works when I put it directly in Microsoft SQL Server Management Studio (it returns the datas).
Here is my code :
<?php
require('conn.php');
if(isset($_POST['submit-search'])){
$search = $_POST['search'];
$sql = "SELECT codepo, codepsa, controle, FORMAT(date, 'dd-MM-yyyy hh:mm:ss') as date FROM dbo.codebarre where datediff(day, date, '$search') = 0";
var_dump($sql);
$result = sqlsrv_query($conn2, $sql);
$queryResult = sqlsrv_num_rows($result);
?>
(...)
<?php
if($queryResult > 0){
while($donnees = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
?>
<tbody>
<tr>
<th style="font-weight: normal;"><?php echo htmlspecialchars($donnees['codepo']); ?></th>
<td><?php echo htmlspecialchars($donnees['codepsa']); ?></td>
<td <?php if ($donnees['controle'] === 'NOK') {
echo 'style="color: red; font-weight: bold"';
} ?>><?php echo htmlspecialchars($donnees['controle']); ?></td>
<td><?php echo $donnees['date'] ?></td>
</tr>
</tbody>
<?php
}
} else {
echo "No data";
}
}
The var_dump($sql) returns me this :
string(138) "SELECT codepo, codepsa, controle, FORMAT(date,
'dd-MM-yyyy hh:mm:ss') as date FROM dbo.codebarre where datediff(day,
date, '20210107') = 0"
As I told you when I paste it in Management studio it works, so I don't understand why it doesn't here.
You have two options:
Execute sqlsrv_query() with the appropriate cursor type, if you want to get the exact number of the returned rows.
Use sqlsrv_has_rows() if you want to check if there are rows returned.
PHP code using sqlsrv_num_rows():
<?php
...
$result = sqlsrv_query($conn2, $sql, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
$queryResult = sqlsrv_num_rows($result);
if ($queryResult > 0) {
// Fetch data
}
...
?>
PHP code using sqlsrv_has_rows():
<?php
...
$result = sqlsrv_query($conn2, $sql);
$queryResult = sqlsrv_has_rows($result);
if ($queryResult) {
// Fetch data
}
...
?>
As an additional note, always use parameterized statements to prevent possible SQL injection issues. As is mentioned in the documentation, function sqlsrv_query() does both statement preparation and statement execution and can be used to execute parameterized queries.
<?php
...
$sql = "
SELECT codepo, codepsa, controle, FORMAT(date, 'dd-MM-yyyy hh:mm:ss') AS date
FROM dbo.codebarre
WHERE datediff(day, date, ?) = 0
";
$params = array($search);
$options = array("Scrollable" => SQLSRV_CURSOR_KEYSET);
$result = sqlsrv_query($conn2, $sql, $params, $options);
...
?>

How to display data from SQL Server

I can get the connection but the data does not show. Some error occurs at this line:
if($result ->num_rows > 0)
The table names for this database is "ndtatt".
This table has 4 columns. And that just one example the value stored in this database.
varchar CARDNO = value 009145
varchar STAFF = value V0822
varchar NAME = value Marry
Varchar ATTDATE = value 2020/01/04
.
<?php
$serverName = "LAPTOP-61BF65AR";
$connectionInfo = array("Database"=>"LocalDatabase");
$conn = sqlsrv_connect ($serverName, $connectionInfo);
if ($conn) {
echo " Connection established.<br/>";
}else{
echo "Connection Failed.<br />";
die(print_r (sqlsrv_errors() , true));
}
$attDate = $_GET['attDate'];
$cardNo = $_GET['cardNo'];
$sql = "SELECT * FROM ndtatt WHERE ATTDATE = '$attDate' AND CARDNO = '$cardNo'";
$result = sqlsrv_query ($conn, $sql);
if($result ->num_rows> 0)
{while($row = $result->fetch_assoc())
{?>
<tr>
<td><?php echo $row['CARDNO']; ?></td>
<td><?php echo $row['STAFF']; ?></td>
<td><?php echo $row['NAME']; ?></td>
<td><?php echo $row['ATTDATE']; ?></td>
</tr>
<?php
}}
else {echo "0 results";}
$conn->close();
?>
Below this is the html file :
<form method="GET" action="get3.php">
<h3 class="absolute" > Attendance Date :
<input type="date" name="attDate"> </h3>
</br></br></br>
<h3 class="absolute2" > Card Number :
<input type="text" name="cardNo" placeholder="Card Number"> </h3>
</br></br></br></br></br>
<center> <input type="submit" name="search" value="Search" class="button" /> </center>
</form>
The first source codes was originally for php(xampp) database with html, but I have made some changes in it, because I want to change the database(php) into sql server.
Do I need to change the entire source codes or just make some changes like I have done in the source codes given?
Does XAMPP have anything to do with SQL Server? I mean, to use the SQL server, do I need to open XAMPP when to run the codes?
XAMPP is an Apache distribution containing MariaDB, PHP and Perl, so the only thing that you need to connect to SQL Server, is to install the PHP Driver for SQL Server (you are using sqlsrv_ functions in your code).
But you have some issues with your code:
You need to use only sqlsrv_ functions. The calls to $result->num_rows, $result->fetch_assoc() and $conn->close() will raise an error.
You need to use "ReturnDatesAsStrings" => true as a connection option to fetch the date/time values as strings (the default value is false and the values of date/time columns are returnded as PHP DateTime objects).
The date values in your table are stored as text, so you need to transform the value of the input elements of type "date" to match the format in the table (yyyy-mm-dd). As a side note, if possible, do not store date values as text. Use the appropriate data types - date or datetime2 in this case.
Always try to use parameters in your statements to prevent SQL injection issues. As is mentioned in the documentation, the sqlsrv_query() function does both statement preparation and statement execution, and can be used to execute parameterized queries.
Example, based on the code in the question:
<?php
// Connection
$serverName = "LAPTOP-61BF65AR";
$connectionInfo = array(
"ReturnDatesAsStrings" => true,
"Database" => "LocalDatabase"
);
$conn = sqlsrv_connect($serverName, $connectionInfo);
if ($conn) {
echo " Connection established.<br/>";
} else {
echo "Connection Failed.<br />";
echo "Error (sqlsrv_connect): ".print_r(sqlsrv_errors(), true);
exit;
}
// Query
$attDate = DateTime::createFromFormat('Y-m-d', $_GET['attDate'])->format('Y/m/d');
$cardNo = $_GET['cardNo'];
$sql = "SELECT * FROM ndtatt WHERE ATTDATE = ? AND CARDNO = ?";
$params = array($attDate, $cardNo);
$result = sqlsrv_query ($conn, $sql, $params);
if ($result === false ) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
// Fetch data
if (sqlsrv_has_rows($result)) {
while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
?>
<tr>
<td><?php echo $row['CARDNO']; ?></td>
<td><?php echo $row['STAFF']; ?></td>
<td><?php echo $row['NAME']; ?></td>
<td><?php echo $row['ATTDATE']; ?></td>
</tr>
<?php
}
} else {
echo "0 results";
}
// End
sqlsrv_free_stmt($result);
sqlsrv_close($conn);
?>
Notes:
The code from the question is driver specific, but you may try to rewrite this code using PDO (PHP Data Objects). With PDO, using the new code, you can use any supported database (of course you need to install a database-dependant driver that implements the PDO interface).
The query below will retrieve two table data with join:
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

What is the procedural mysqli way of preparing SQL statements?

I have a SQL query in my code that I want to convert to a prepared statement to stop vulnerabilities like SQL injections. So this is what I want to convert:
<?php
$query = "SELECT * from `wp_posts` WHERE ID=$pid ";
$result = mysqli_query($link, $query);
//$id=$row['Gallery_Id'];
while($row = mysqli_fetch_array($result)){
?>
<h2 align="center"> <?php echo $row['post_title']; ?> </h2><br>
<div class="paracenter">
<p id="cont"><?php echo $row['post_content']; ?></p>
<hr color="black" width="10%">
</div>
<?php } ?>
This is what I tried, but it doesn't work.
$query = "SELECT * from `wp_posts` WHERE ID=? ";
$stmt = mysqli_prepare($link, $query);
if($stmt){
mysqli_stmt_bind_param($stmt, "i", $pid);
mysqli_stmt_bind_result($stmt, $dbpid);
mysqli_stmt_execute($stmt);
mysqli_stmt_fetch($stmt);
}
$result = mysqli_query($link, $query);
//$id=$row['Gallery_Id'];
while($row = mysqli_stmt_fetch($result)){
?>
<h2 align="center"> <?php echo $row['post_title']; ?> </h2><br>
<div class="paracenter">
<p id="cont"><?php echo $row['post_content']; ?></p>
<hr color="black" width="10%">
</div>
<?php } ?>
Almost all the examples online doesn't use the procedural method I use. How can I rectify this?
To protect your query against injection attack, you have two options. The first is super simple and just as secure as a prepared statement.
Cast $pid as an integer.
$query = "SELECT post_title, post_content FROM wp_posts WHERE ID = " . (int)$pid;
Secure and done.
How to write a prepared statement with result binding... (I don't use procedural mysqli syntax)
if (!$stmt = $link->prepare("SELECT post_title, post_content FROM wp_posts WHERE ID = ?")) {
echo "Syntax Error # Prepare"; // $link->error; <-- never show actual error details to public
} elseif (!$stmt->bind_param("i", $pid) || !$stmt->execute() || !$stmt->bind_result($title, $content)) {
echo "Syntax Error # ParamBind | Execute | ResultBind"; // $stmt->error; <-- never show actual error details to public
} else {
while ($stmt->fetch()) {
echo "<div>";
echo "<h2 align=\"cente\">$title</h2><br>";
echo "<div class=\"paracenter\">";
echo "<p id=\"cont\">$content</p>";
echo "<hr color=\"black\" width=\"10%\">";
echo "</div> ";
}
}
Some additional notes.
If you are not going to use result binding, you should use mysqli_fetch_assoc() instead of mysqli_fetch_array(). mysqli_fetch_array() will generate a bloated result set of both indexed and associative keyed elements (double what you actually need).
When you use bind_result(), you need to replace * in the SELECT clause with the columns to be extracted.
My first elseif() expression contains three separate calls & checks on $stmt. As soon as any one of those calls returns a falsey/erroneous response, the conditional expression short circuits and the remaining calls in the expression are never executed.
If adopting my object-oriented mysqli style, be sure to align your database connection syntax as object-oriented as well.

I suspect a PHP-SQL error in the code below

This block of codes is supposed to retrieve data from my database using password already stored in the table. For some passwords, entered via a web form, it behaves properly. For others, it doesn't. I spent a good time trying to fix it, but could not.
<?php
include('connect.php');
$login = $_POST['login'];
$query = mysql_query("select * from secure_table where myPass = $login");
$row = mysql_fetch_array($query));
if( $_POST['login'] = $row['myPass'])
{
echo"<div align ='center'>";
echo "Your Details are:";
echo $row['surName'];
echo"<br/>";
echo $row['firstName'];
echo"<br/>";
echo $row['myDepartment'];
echo"</div>";
}
else{
echo "<div align = 'center'>;
<h2>Error in Password</h2>
</div>";
}
mysql_close($connection)
?>
and you need to change this line as well
if( $_POST['login'] = $row['myPass'])
To this
if( $_POST['login'] == $row['myPass'])
//use double equal for comparison. single equal is assignment operator.
$query = mysql_query("select * from secure_table where myPass = $login");
your query is wrong if $login is not and integer
change to this
$query = mysql_query("select * from secure_table where myPass = '$login'");
check this link
http://dev.mysql.com/doc/refman/5.0/en/identifier-qualifiers.html
you have extra ) remove this in this line
$row = mysql_fetch_array($query));
to this
$row = mysql_fetch_array($query);
as it written and The One and Only ChemistryBlob pointed it out remove the semicolumn ; in the
else statement from this line
echo"<div align = 'center'>;
one more think mysql_ function are depricited.
use mysqli_ Function or PDO
For mysqli_ function check this link http://php.net/manual/en/book.mysqli.php
FOR PDO check this link http://php.net/manual/en/book.pdo.php

Categories