I want to print result of a Mysqli query, But when I try to do as following way, It does not return any values or error. The code does not go through the while loop. What would be the wrong with my code, Please help me!
<?php
$mysqli = new mysqli("localhost", "root", "", "domains");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$part = explode(".", $str);
$part1 = $part[0];
$part2 = $part[1];
$sql = "SELECT
DomainCategory.Name
FROM
DomainName_Client,
DomainNameType,
DomainCategory,
OrderDomain_Client
WHERE
DomainName_Client.Name = '$part1'
AND DomainNameType.Name = '$part2'
AND DomainName_Client.TypeID = DomainNameType.ID
AND DomainCategory.ID = DomainName_Client.DomainCategoryID
AND OrderDomain_Client.DomainNameID = DomainName_Client.ID";
$result = $mysqli->query($sql);
if (!$result = $mysqli->query($sql)) {
die('There was an error running the query ' . $mysqli->error . ']');
}
while ($row = $result->fetch_assoc()) {
echo 'Total results: ' . $result->num_rows;
}
?>
First you check the number of results returning in the sql query using the following code and after that you print it using while or for loop.
echo $result->num_rows;
Related
<?php
$mysqli = new mysqli("localhost", "root", "", "titan3d");
if (mysqli_connect_error()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sdate = "";
$stime = "";
if(isset($_POST['sdate']))
{
$sdate = $_POST["sdate"];
}
if(isset($_POST['stime']))
{
$stime = $_POST["stime"];
}
$statement = $mysqli->prepare("SELECT bookedseat FROM bookings WHERE sdate = ? AND stime = ?");{
$statement->bind_param("si", $sdate, $stime);
if (!$statement->execute()) {
trigger_error('Error executing MySQL query: ' . $statement->error);
}
$statement->bind_result($book);
$statement->fetch();
printf($book);
//header('Location: http://localhost/My%20Project/seats.html');
$statement->close();
}
$mysqli->close();
?>
This is my php file made to get the data from a form and make a query and then display the results.
When executed,the php works perfectly.
But it only displays the first value in the query.
Why is it?
How can I display all the values in my query?
You need to use $stmt->fetch() in a while loop, you can then iterate over each the returned row.
while ($stmt->fetch()) {
// $book will have the value of bookedseat for the current row
}
i have SQL query :
SELECT countryCode FROM itins_countries WHERE (itinID = 5);
$countriesIndex = mysql_fetch_array($countriesQuery);
now, in another art of my code I would like to run on the "$countriesIndex" and print all the values it contain ("countryCode");
how can i do that?
while($row = mysql_fetch_array($countriesQuery)){
echo $row['column_name'];
///same for other columns
}
you can use the while loop to loop until all the array element has been printed
try this....
echo "<pre>";print_r($countriesIndex);
mysql_connect is deprecated...you can use mysqli_connect.
$mysqli = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno($mysqli)) {
trigger_error('Database connection failed: ' . mysqli_connect_error(), E_USER_ERROR);
}
mysqli_set_charset($mysqli, "utf8");
$sql = "SELECT countryCode FROM itins_countries WHERE (itinID = 5)";
$result = mysqli_query($mysqli, $sql);
$countries = [];
while($row = $result->fetch_assoc())
{
$users_arr[] = $row;
}
$result->close();
print_r($users_arr);
I'm building a simple form and want to secure this against the following SQL-injections:
- blind-injection
- boolean-based
- blind injection
- UNION query-based
- Stacked queries
- error-based injections
I thought that I had it all secured, but when I run SQL-map it still exploits my database.
<?php
$input = $_GET['input'];
if ($input) {
$db = mysqli_connect("localhost", "sec", "dubbelgeheim", "bookshop");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$escaper = real_escape_string($input);
$statement = $db->prepare("SELECT * FROM productcomment WHERE ProductId = ? LIMIT 1");
$statement->bind_param("s", $escaper);
$statement->execute();
$result = $statement->get_result();
$statement->close();
$count = $result->num_rows;
if ($count > 0) {
while ($row = $result->fetch_assoc()) {
echo "Product:" . $row['ProductId'] . "<br>";
echo "Annotation:" . $row['Comment'] . "<br>";
echo "TestOK!<br>";
}
}
else {
echo 'No record!';
}
$result->free();
$db->close();
}
?>
Did I forget something?
Can anyone help?
Thanks in advance!
Your problem is caused by you displaying mysqli_connect_error(). This is OK for testing but should NOT be used in production code. You also don't need $escaper = real_escape_string($input);.
Try this instead
/* check connection */
if (mysqli_connect_errno()) {
file_put_contents('MySQLiErrors.txt',date('[Y-m-d H:i:s]'). mysqli_connect_error()."\r\n", FILE_APPEND);
exit();
}else{
$statement = $db->prepare("SELECT * FROM productcomment WHERE ProductId = ? LIMIT 1");
$statement->bind_param("s", $input);
}
I have a working SQL query that I'm trying to use in a small PHP script but getting Parse error, tried many variations. Hope you can help. End result would be to have a two field form with 'Date' and 'Channel No' then giving result count of number of 'channel' rows for a given date. Sorry fairly new PHP/SQL, thanks.
<?php
// Connect to MSSQL and select the database
$link = mssql_connect('localhost', 'root', '', 'jm_db');
mssql_select_db('jm_db');
// Select all our records from a table
$mysql_query = mssql_query ('SELECT COUNT(*) FROM asterisk_cdr
WHERE calldate LIKE '%2014-10-11%'
AND channel LIKE '%SIP/4546975289%');
echo $sql;
?>
I have re-done the code but getting 'Warning: mysql_fetch_array() expects parameter 1 to be resource' and undefined variable.
<?php
// Create connection
$mysqli = new mysqli($localhost, $root, $jm_db);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = ("SELECT COUNT(*) FROM asterisk_cdr
WHERE calldate LIKE '%2014-10-11%'
AND channel LIKE '%SIP/4546975289%'");
$results= array();
while ($result = mysql_fetch_array($sql)) {
$results[]= $result;
}
foreach($results as $result){
echo $result['calldate'] . " " . $result['channel'];
}
?>
You're missing a quote (Stack's syntax highlighting shows you), yet it should be replaced with an opening double quote and ending with the same. You can't use all single quotes.
I replaced the opening single quote with a double, along with a matching closing double quote.
$mysql_query = mssql_query ("SELECT COUNT(*) FROM asterisk_cdr
WHERE calldate LIKE '%2014-10-11%'
AND channel LIKE '%SIP/4546975289%'");
As a sidenote, you're echoing the wrong variable.
However, that is not how you would echo out results, but with a loop.
Something like, and replacing Fieldname with the one you want to use:
while ($row = mssql_fetch_assoc($mysql_query)) {
print $row['Fieldname'] . "\n";
}
or use mssql_fetch_array()
You can also use:
$results= array();
while ($result = mssql_fetch_array($mysql_query)) {
$results[]= $result;
}
foreach($results as $result){
echo $result['calldate'] . " " . $result['channel'];
}
For more information on Microsoft SQL Server's function, consult:
http://php.net/manual/en/book.mssql.php
$mysql_query = mssql_query ('SELECT COUNT(*) FROM asterisk_cdr
WHERE calldate LIKE '%2014-10-11%'
AND channel LIKE '%SIP/4546975289%');
while($row=mssql_fetch_array($mysql_query))
{
echo $row[0];
}
$mysqli = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$mysql_query = mysqli ("SELECT COUNT(*) FROM asterisk_cdr WHERE calldate LIKE '%2014-10-11%' AND channel LIKE '%SIP/4546975289%'");
while ($row = mysql_fetch_array($mysql_query, MYSQL_ASSOC)) {
echo ($row["channel"]);
}
this is a simple example with PDO
<?php
try {
$dns = 'mysql:host=localhost;dbname=jm_db';
$user = 'root';
$pass = '';
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
$cnx = new PDO( $dns, $user, $pass, $options );
$select = $cnx->query("SELECT COUNT(*) as count FROM asterisk_cdr WHERE calldate LIKE '%2014-10-11%' AND channel LIKE '%SIP/4546975289%'");
$select->setFetchMode(PDO::FETCH_OBJ);
while( $row = $select->fetch() )
{
echo '<h1>', $row->count , '</h1>';
}
} catch ( Exception $e ) {
echo "Connect failed : ", $e->getMessage();
die();
}
I have tried the following code to output each student father_contact by firstly merging them and secondly separating each number by comma and could not make it working. Please help me.
$sql = "SELECT Fathers_Contact FROM student WHERE Class ='$class' AND Section='$s' and Year='$y'";
$result = mysql_query($sql);
if (!$result) {
die("Query not working");
}
$mbno_arr = array();
while ($row = mysql_fetch_array($result)) {
$mbno_arr[] = $row[0];
}
$mbno_list = implode(',', $mbno_arr);//expect here is: 9867656543,9867656443,9867654543
if(empty($mbno_list)){
echo "No number is there";
exit;
}
if(empty($msg)){
echo "Message empty!";
exit;
}
Father_contact is ten digit mobile no.
// Escapes special characters in a string for use in an SQL statement
$SQL = sprintf(
"SELECT Fathers_Contact
FROM student
WHERE Class = '%s' AND Section = '%s' and Year = '%s'",
mysql_real_escape_string($class),
mysql_real_escape_string($s),
mysql_real_escape_string($y)
);
// Result or die (print mysql error)
$result = mysql_query($SQL) or die( mysql_error() );
// Check if result has rows
if( mysql_numrows($result) > 0 )
{
$mbno_arr = array();
while ( $row = mysql_fetch_array($result) )
$mbno_arr[] = $row[0];
if( count($mbno_arr) > 0)
echo implode(',', $mbno_arr);
else
echo 'No number is there';
}
else
{
echo 'No result for query';
}
// free result
mysql_free_result($result);
NB use PDO or mysqli. mysql_* is deprecated
Firstly, mysql_* is now officially deprecated. Please use PDO or MySQLi.
Can you try this:
<?php
// Connect
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Query
$query = "SELECT Fathers_Contact FROM student WHERE Class = ? AND Section = ? and Year = ?";
if ($stmt = $mysqli->prepare($query)) {
{
// Bind params
$stmt->bind_param("sss",
$class,
$s,
$y);
// Execute statement
$stmt->execute();
// fetch associative array
$mbno_arr = array();
$result = $stmt->fetch_result();
while ($row = $result->fetch_assoc())
{
// Build data
$mbno_arr[] = $row['Fathers_Contact'];
}
// close statement
$stmt->close();
// Debug?
$mbno_list = implode(',', $mbno_arr);
if (empty($mbno_list)) {
echo "No number is there";
} else {
echo "Query Results: $mbno_list";
}
}
// Close Connection
$mysqli->close();
?>