<?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
}
Related
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;
I have an address table and one of the fields is an image blob. When I update a record through $POST and include an image, everything works. However if no image is included in $POST, I want to reuse the image that is already stored in the record. This is were im having problems. when I run the code below it does not update the image file. here's my code.
function UpdateRecordfromPost()
{
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$FirstName = test_input($_POST['fname']);
$LastName = test_input($_POST['lname']);
$Address = test_input($_POST['address']);
$Town = test_input($_POST['town']);
$Postcode = test_input($_POST['pcode']);
$Phone = test_input($_POST['phone']);
$Email = test_input($_POST['email']);
$ID = ($_POST['idname']);
}
$mysqli = new mysqli( $GLOBALS['servername'], $GLOBALS['username'], $GLOBALS['password'], $GLOBALS['dbname']);
if ($mysqli->connect_error)
{
die("Connection failed: " . $mysqli->connect_error);
}
$image = GetimagefromPost(); //this function returns a image and seems to work
if ($image == "")
{
$image = Saveimaqgefile($ID);
}
$query = "UPDATE addressbook SET firstname='$FirstName',lastname='$LastName',street='$Address',town='$Town',PostCode='$Postcode',phone='$Phone',email='$Email',Photo='$image' WHERE id='$ID'";
if ($result = $mysqli->query($query))
{
echo "Updated record successfully";
}
else
{
echo "Error: " . $query . "<br>" . $mysqli->error;
}
$mysqli->close();
}
function Saveimaqgefile($file_id) {
$mysqli = new mysqli( $GLOBALS['servername'], $GLOBALS['username'], $GLOBALS['password'], $GLOBALS['dbname']);
if ($mysqli->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql= "SELECT * from ".$GLOBALS['dbname']. " WHERE id=".$file_id;
$result = $mysqli->query($sql);
if ($result->num_rows > 0)
{
$row=mysqli_fetch_array($result);
}
else { $row = "";}
$mysqli->close();
return base64_encode($row['Photo']);
}
This is my first question, sorry if i've done something wrong
You'd need conditional logic.
if (image was uploaded) {
mysqli_query('... update record with new image ...;);
} else {
mysqli_query('... update record WITHOUT image data ...');
}
For most other types of (small) data, you could do it in a single query, e.g.
UPDATE ... SET field=IF($newdata = '', field, $newdata)
but your image blob is likely to be HUGE, and you don't want to repeat it twice in the same query string.
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();
?>
The company database has duplicate entries for ID due to different locations so I'm trying to return the database queries on the website by ID # AND zip matches. I can get the the code to query the database and not return an error but it won't return the values in the results(only blank entries) from the row it found.
Any ideas?
$mysqli = new mysqli($host, $user, $password, $dbname);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$searchTerm = $_GET['term']; // GET the search term submitted by the form
$zip = $_GET['term1'];
$customerNumber = '';
$progID = '';
$balance = '';
$sql = "Select cust_no, zip From teecust where cust_no=? and zip=?";
// Create the prepared statement
if($stmt = $mysqli->prepare($sql)){
$stmt->bind_param("ss", $searchTerm, $zip); // bind the search term to the query where the '?' once was
if(!$stmt->execute()){ // run the query
echo $mysqli->error;
};
$stmt->bind_result($customerNumber, $progID, $balance); // retrieve results into variables
while($stmt->fetch()){ // loop through results
// You now have the result in $customerNumber, $progID, and $balance - do what you want with it
echo "Customer number: " . $customerNumber . "<br>Date last updated on: " . $progID . "<br> Balance: <strong>$" . $balance . "</strong> ";
}
$stmt->close();
}
else{
echo $mysqli->error;
}
?>
I have one function selecting a load of information from one table. This then launches another function to get some info from another table.
Here's the shortened code:
$con = new mysqli("localhost", "user", "password");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$con->select_db("stories_test");
getStories($con);
function getStories($con) {
... //get's a load of data from one table
$result = getStoryName($con, $stringstoryid);
... //More stuff here
}
function getStoryName($con) {
$newquery = "SELECT storyname, genre FROM stories WHERE storyid = 'Anewstory9856'";
if ($stmt = $con->prepare($newquery)) {
echo $newquery;
$stmt->execute();
$stmt->bind_result($storname, $genre);
while ($stmt->fetch()) {
$resultarray = array (
'storname' => $storname,
'genre' => $genre
);
}
}
else {
echo 'statement failed';
}
return $resultarray;
}
All I ever get is 'statement failed' from the second query.
I have tried the exact same query in a separate script on its own and it works fine, but here it seems to fail at 'prepare'.
Does anyone have any clues?