This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 2 years ago.
I get lost when I need to prepare multiple statements. I have problems with prepared statement and connection..
I have a function and I pass to it the connection to the database ($con variable). Inside this function i prepare more statement but i have an error, the server replied with:
mysql_error() expects parameter 1 to be resource, object given in select.php on line 1086
This is the page where i call the function and pass the connection variable:
include('include/connect.php');
echo show_volanti($con);
This is the connection file that I included above:
$con = mysqli_connect($host,$user,$password,$db);
if (!$con) {
die('Connection Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error()); }
if(!mysqli_set_charset($con, "utf8mb4")) {
printf("Error loading character set utf8: %s\n", mysqli_error($con));
exit(); }
and this is the function:
function show_volanti($data){
$con = $data; // PASSO CONNESSIONE
$con2 = ''; // SECONDA CONNESSIONE
$id = 1; // 1 VOLANTE
$visibile = 1; // VARIABILE DI VISIBILITA'
$rows1 = array(); // PREPARO ARRAY 1 PER ID ARTICOLI VOLANTE
$rows2 = array(); // PREPARO ARRAY 2 PER ARTICOLI VOLANTE
$rows3 = array(); // PREPARO ARRAY PER GALLERIA IMMAGINI ARTICOLI
$stmt1 = ''; // PREPARO GLI STATEMENT
$stmt2 = ''; // PREPARO GLI STATEMENT
$stmt3 = ''; // PREPARO GLI STATEMENT
$g = ''; // RIFERIMENTO ASSOCIAZIONE GALLERY VIEWER
$id_articoli = array(); // IMMAGAZZINO ID ARTICOLI DA RECUPERARE NELLA GALLERIA
$con2 = mysqli_stmt_init($con); // INIZIALIZZO LA CONNESSIONE
$stmt1 = mysqli_stmt_prepare($con2,'SELECT
articoli.id
FROM articoli
WHERE articoli.genere1 = ?
AND articoli.visibile = ?')
or die(mysql_error($con2));// QUERY INSERIMENTO DATI
mysqli_stmt_bind_param($stmt1,'ii',$id,$visibile); // LEGO I PARAMETRI
mysqli_stmt_execute($stmt1); // ESEGUO LA QUERY
mysqli_stmt_bind_result($stmt1,$rows1['id']);
while(mysqli_stmt_fetch($stmt1)){
$id_articoli = $rows1['id'];
}
// CREO RIFERIMENTO PER GALLERIA NEL VIEWER
$g .= "g";
$g .= $id_articoli;
$stmt2 = mysqli_stmt_prepare($con2,'SELECT
articoli.id,
articoli.titolo,
articoli.descrizione
FROM articoli
WHERE articoli.genere1 = ?
AND articoli.visibile = ? ')
or die(mysqli_error($con2)); // QUERY INSERIMENTO DATI
mysqli_stmt_bind_param($stmt2,'ii',$id,$visibile); // LEGO I PARAMETRI
mysqli_stmt_execute($stmt2); // ESEGUO LA QUERY
mysqli_stmt_bind_result($stmt2,$rows2['id'],$rows2['titolo'],$rows2['descrizione']);
// PREPARO QUERY PER LA GALLERIA
$stmt3 = mysqli_stmt_prepare($con2,'SELECT
galleria.id,
galleria.foto
FROM galleria
WHERE galleria.rif_id = ?
AND articoli.visibile = ? ')
or die(mysqli_error($con2)); // QUERY INSERIMENTO DATI
mysqli_stmt_bind_param($stmt3,'ii',$id_articoli,$visibile); // LEGO I PARAMETRI
mysqli_stmt_execute($stmt3); // ESEGUO LA QUERY
mysqli_stmt_bind_result($stmt3,$rows3['id'],$rows3['foto']);
$html = "";
$html .= "<div class='container'>";
$html .= " <div class='row'>";
$html .= " <div class='col-sm-12'>";
$html .= " <div class='panel panel-default'>";
$html .= " <div class='panel-body'>";
while (mysqli_stmt_fetch($stmt2)){
$html .= " <div class='col'>";
$html .= " <div class='panel panel-default'>";
$html .= " <div class='panel-heading'>$rows2[titolo]</div>";
$html .= " <div class='panel-body'>";
$html .= " <div class='row'>";
$html .= " <div class='class_p'>$rows2[descrizione]</div>";
$html .= " <div> <!-- end first row -->";
$html .= " <div class='class_container clearfix'>";
while(mysqli_stmt_fetch($stmt3)){
$html .= " <div class='thumbnail col-sm-2'>";
$html .= " <div class='class_img'>";
$html .= " <a href='$rows3[foto]' data-toggle='lightbox' data-gallery='$g' >";
$html .= " <img src='$rows3[foto]' class='img-responsive' class='img-fluid'>";
$html .= " </a>";
$html .= " </div> <!-- end class_img -->";
$html .= " </div> <!-- end thumbnail col-sm-2- -->";
}
$html .= " </div> <!-- end class_container -->";
$html .= " </div> <!-- end panel body -->";
$html .= " </div> <!-- end panel panel-default -->";
$html .= " </div> <!-- end col -->";
}
$html .= " </div> <!-- end panel-body -->";
$html .= " </div> <!-- end panel panel-default -->";
$html .= " </div> <!-- end col-sm-12 -->";
$html .= " </div> <!-- end row -->";
mysqli_close($con2); // CHIUDO CONNESSIONE
return $html;
}
This results in the error:
$stmt1 = mysqli_stmt_prepare($con2,'SELECT
articoli.id,
FROM articoli
WHERE articoli.genere1 = ?
AND articoli.visibile = ?')
or die(mysql_error($con2));// QUERY INSERIMENTO DATI
Change mysql_error to mysqli_error and your problem should be fixed.
Note: Using or die() is a bad way to handle an error.
Related
I'm using SQL and PHP to pull information from my database and it returned a list of users that met the criteria. And I need to redirect to another page using the selected amount from the picture below. How can I grab this amount to another page?
For example, when I click the first select, I can go to the other page that showing $24, and Rubinsztein Abdel, 182 Crownhardt Lane...
<!--loader end-->
<!-- Main -->
<div id="main">
<!-- wrapper -->
<div id="wrapper">
<div class="content">
<!-- Map -->
<div class="map-container column-map right-pos-map">
<div id="map-main"></div>
<ul class="mapnavigation"></ul>
<div class="scrollContorl mapnavbtn" title="Enable Scrolling"><span><i class="fa fa-lock"></i></span></div>
</div>
<!-- Map end -->
<!--col-list-wrap -->
<div class="col-list-wrap left-list">
<!-- list-main-wrap-->
<div class="list-main-wrap fl-wrap card-listing">
<!-- listing-item -->
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$severname = "localhost";
$username = "root";
$password = "";
$dbname = "dbn";
//$conn = mysqli_connect('xx', 'xx', 'xx','xx');
$conn = mysqli_connect('dxx', 'xx', 'xx','xx');
//check connection
if (mysqli_connect_errno())
{echo nl2br("Failed to connect to MySQL: ". mysqli_connect_error() . "\n"); }
else
{ echo nl2br("");}
$city = mysqli_real_escape_string($conn, $_POST['city']);
$date1 = mysqli_real_escape_string($conn, $_POST['date1']);
$date2 = mysqli_real_escape_string($conn,$_POST['date2']);
$pet = mysqli_real_escape_string($conn, $_POST['pet']);
//var_dump($date2);
$sql = "SELECT CONCAT(s.lname, ' ', s.fname) AS fullName, s.ratings, s.rate, s.phone, s.address FROM Pet_Sitter AS s WHERE s.citystate='".$city."' AND s.pet_type='".$pet."' "
;
//echo $sql."<br/>";
$result = mysqli_query($conn,$sql);
if (!$result) {
printf("Error: %s\n", mysqli_error($conn));
exit();
}
if ($result=mysqli_query($conn,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
printf("");
}
//var_dump($result);
$num_rows = mysqli_num_rows($result);
?> <div class="container"> <?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
//var_dump($row);
// echo "<tr><td>" . $row['fullName'] . " </td><td>" . $row['ratings'] . " </td><td>" . $row['rate'] . " </td></tr>";
// echo '<div class="listing-item">';
echo '<div class="listing-item">';
echo '<article class="geodir-category-listing fl-wrap">';
echo '<div class="geodir-category-img">';
echo '<img src="../images/all/1.jpg" alt="">';
echo '<div class="overlay"></div>';
echo '<div class="list-post-counter"><span>' . $row['rate'] . '</span></div>';
echo '</div>';
echo '<div class="geodir-category-content fl-wrap">';
echo '<a class="listing-geodir-category" href="../index.html">Pet sitting</a>';
echo '<h3>' . $row['fullName'] . '</h3>';
echo '<p>PET-SITTER INFORMATION</p>';
echo '<div class="geodir-category-options fl-wrap">';
echo '<span>' . 'Reviews ' . $row['ratings'] .'</span>';
echo '<div class="geodir-category-location">'. $row['address'] . " · " . $row['phone'] .
'</div>';
echo '</div>';
echo '</div>';
echo '</article>';
echo '</div>';
}?>
<?php
} else {
echo "0 results";
}
mysqli_close($conn);
?>
</div>
</div>
An easy way to do it is to create one page (the one you wanna go if you click on your items) and use GET on URL to get the page id;
On your actual page you will use a link like :
<a href="new-page.php?id=<?php echo $row['id']; ?>"
Here the ?id= on URL is a parameter, that you can get on the other page :
$pageId = $_GET['id'];
Then, you just have to make a SQL request
SELECT * FROM Pet_Sitter WHERE id=$pageId
(better to use prepare and execute for this request as the value of $pageId can be change by everybody by changing the URL).
So every time you click on a link, the page will display the matching informations.
Also you should closed <?php when you are writing HTML instead of using a lot of echo.
Please check out php code given below.
<?php
$con = mysqli_connect('localhost', 'root', '', 'unityaccess');
if (mysqli_connect_errno()) {
echo "connection failed";
exit();
}
$query = "SELECT * FROM players ORDER BY id DESC";
$row_result = mysqli_query($con, $query);
while($record = mysqli_fetch_assoc($row_result)){
$card = '<div class="card">';
$card .= '<div class="card-body">';
$card .= '<div class="comment-header">';
$card .= '<h6 class="card-subtitle mb-2 comment-name">'.$record['name'].' </h6>';
$card .= '</div>';
$card .= '</div>';
$card .= '</div>';
}
?>
I want to loop all name values inside html cards. according to loop there have 7 all name values. when I echo them it will loop correctly. but when I concatenate & echo $card like follows.
<div class="row">
<div class="col-md-12 comment-section">
<h4>Comments</h4>
<?php
echo $card;
?>
</div>
</div>
Then I can only show first value of name attribute. Why I can't retrieve all the name values with card. I think code looks not bad anyway.
change
$card = '<div class="card">';
with
$card .= '<div class="card">';
*It is a good practice to initialize your variables, if you don't the PHP engine will do a type cast depending on variable usage.
You are overwriting the $card variable each time round the loop, so all you are left with after the loop is the last card.
$row_result = mysqli_query($con, $query);
$card = ''; // init the card variable, so you can use `.=` from here on
while($record = mysqli_fetch_assoc($row_result)){
//$card = '<div class="card">'; this was the offending line
$card .= '<div class="card">';
$card .= ' <div class="card-body">';
$card .= ' <div class="comment-header">';
$card .= ' <h6 class="card-subtitle mb-2 comment-name">'.$record['name'].' </h6>';
$card .= ' </div>';
$card .= ' </div>';
$card .= '</div>';
}
I have this code that I use to fetch data from a database:
function show_volanti($data){
$con = $data; // PASSO CONNESSIONE
$id = 1; // 1 VOLANTE
$visibile = 1; // VARIABILE DI VISIBILITA'
$rows1 = array(); // PREPARO ARRAY 1 PER ID ARTICOLI VOLANTE
$rows2 = array(); // PREPARO ARRAY 2 PER LE FOTO VOLANTI
$id_articoli = ''; // RIFERIMENTO ARTICOLI PER SECONDA QUERY GALLERIA
$g = ''; // RIFERIMENTO ASSOCIAZIONE GALLERY VIEWER
//$rif_id = ''; // RIF_ID SE OK DA CANCELLARE
$query1 = "SELECT articoli.id AS id_articoli,
articoli.titolo,
articoli.descrizione
FROM articoli
WHERE articoli.genere1 = ?
AND articoli.visibile = ?";
$query2 = "SELECT galleria.id AS id_galleria,
galleria.foto,
galleria.rif_id
FROM galleria
WHERE galleria.rif_id = ?";
$stmt = mysqli_stmt_init($con); // INIZIALIZZO LA CONNESSIONE
mysqli_stmt_prepare($stmt,$query1);
mysqli_stmt_bind_param($stmt,'ii',$id,$visibile); // LEGO I PARAMETRI
mysqli_stmt_execute($stmt); // ESEGUO LA QUERY
mysqli_stmt_bind_result($stmt,
$rows1['id_articoli'],
$rows1['titolo'],
$rows1['descrizione']); // CREO RIFERIMENTO PER GALLERIA NEL VIEWER
$html = "";
$html .= "<div class='container'>";
while (mysqli_stmt_fetch($stmt)){
$id_articoli = $rows1['id_articoli'];
$html .= " <div class='row'>";
$html .= " <div class='col-sm-12'>";
$html .= " <div class='panel panel-default'>";
$html .= " <div class='panel-body'>";
$html .= " <div class='col'>";
$html .= " <div class='panel panel-default'>";
$html .= " <div class='panel-heading'><b>$rows1[titolo]</b></div>";
$html .= " <div class='panel-body'>";
$html .= " <div class='row'>";
$html .= " <div class='class_p'>$rows1[descrizione]</div>";
$html .= " <div> <!-- end first row -->";
$html .= " <div class='class_container clearfix'>";
mysqli_stmt_prepare($stmt,$query2);
mysqli_stmt_bind_param($stmt,'i',$id_articoli); // LEGO I PARAMETRI
mysqli_stmt_execute($stmt); // ESEGUO LA QUERY
mysqli_stmt_bind_result($stmt,
$rows2['id_galleria'],
$rows2['foto'],
$rows2['rif_id']);
while(mysqli_stmt_fetch($stmt)){
$g = '';
$g .= "g";
$g .= $rows2['rif_id'];
$html .= "<div class='thumbnail col-sm-2'>";
$html .= "<div class='class_img'>";
$html .= "<a href='$rows2[foto]' data-toggle='lightbox' data-gallery='$g' >";
$html .= "<img src='$rows2[foto]' class='img-fluid'>";
$html .= "</a>";
$html .= "</div> <!-- end class_img -->";
$html .= "</div> <!-- end thumbnail col-sm-2- -->";
}
$html .= "</div> <!-- end class_container -->";
$html .= "</div> <!-- end panel body -->";
$html .= "</div> <!-- end panel panel-default -->";
$html .= "</div> <!-- end col -->";
$html .= "</div> <!-- end panel-body -->";
$html .= "</div> <!-- end panel panel-default -->";
$html .= "</div> <!-- end col-sm-12 -->";
$html .= "</div> <!-- end row -->";
}
mysqli_stmt_close($stmt); // CHIUDO LO STATEMENT
mysqli_close($con); // CHIUDO CONNESSIONE
return $html;
}
The code partially works because it show the result but it only show one result and inside the database i have more results to show so it doesn't work as it should.. May you help me to find the error?
It seems you're reusing the same variables for both external and internal loop. For example, you're using $stmt for both of them. I'm not sure if that's why you're getting only one result (as it may depend on the amount of results you received from each of them), but I would look into that.
As a debug tip, I would remove all code relevant to the external loop and first print out the results of the external ones properly. Once you have that working, start adding the internal loop code and make sure it works. Do not reuse the same variables though.
I'm making a shop as a work for school and I have to add into a database the selections of the customer.
The insert is ok, however, in the CommandeTotal column, the prize is only the one of the last item I choose (I choose 2 or more products who have different prize), here's my code to understand my problem:
The instruction for add into the table Commandes is ok.
The problem is when it's time to do the insert instruction for add into the table commandeDetails, the products are all inserted, but the prize for all the products in the table after the insert instruction is from the last product.
<?php
if (empty($_SESSION["achats"]))
echo "Votre panier est Vide!";
else {
//afficher les éléments du panier
$mysqli = new mysqli("localhost", "root", "", "magasin");
mysqli_set_charset($mysqli, "utf8");
if (isset($_POST["PasserCommande"])) {
//0) Pogner le ID du user logué
if(isset($_SESSION["nom"]))
{
$queryUser = "SELECT MAX(UserID) AS No FROM Users WHERE UserName = '".$_SESSION["nom"]."'";
$resultUser = $mysqli->query("$queryUser");
$UserID = $resultUser->fetch_assoc()["No"];
//1) Ajouter une commande(enlever CommandeID dans la requête)
$queryOrder = "INSERT INTO commandes(UserID, CommandeDate) VALUES('".$UserID."', CURRENT_TIMESTAMP())";
$mysqli->query($queryOrder);
//2) Pogner le ID de la commande
$queryOrderID = "SELECT MAX(CommandeID) AS id FROM commandes";
$result = $mysqli->query($queryOrderID);
$orderID = $result->fetch_assoc()["id"];
echo"<h3>Résultat de votre commande : </h3>";
echo "Commande # " . $orderID . " enregistrée.";
//3) Ajouter des détails
while ($element = each($_SESSION["achats"])) {
if(isset($_SESSION["prix"]))
{
$queryOrderDetail = "INSERT INTO detailcommande(CommandeID, ProduitID, CommandeTotal, CommandeDate) VALUES('".$orderID."','".$element["key"]."', '".$_SESSION["prix"]."', CURRENT_TIMESTAMP())";
$mysqli->query($queryOrderDetail);
echo $queryOrderDetail;
}
}
unset($_SESSION["achats"]);
}
}
if (isset($_SESSION["achats"])) {
$total = 0;
echo"<h3>Vos achats de la journée : </h3>";
while ($element = each($_SESSION["achats"])) {
$query = "SELECT * FROM produits WHERE ProduitID = '" . $element["key"] . "'";
$result = $mysqli->query($query);
$ligne = $result->fetch_assoc();
echo"<div class='col-sm-4 col-lg-4 col-md-4'>
<div class='thumbnail'>
<div class='caption'>";
echo"<img src='IMAGES/max/$ligne[ProduitLien]' width='100' height='50' />
<h4 class='pull-right'>$ligne[ProduitPrix]$</h4>
<h5><a href='#'>$ligne[ProduitNom]</a></h5>
<h6>Qté : $element[value]</h6>
</div>
<div class='ratings'>
<p>
<span class='glyphicon glyphicon-star'></span>
<span class='glyphicon glyphicon-star'></span>
<span class='glyphicon glyphicon-star'></span>
<span class='glyphicon glyphicon-star'></span>
<span class='glyphicon glyphicon-star'></span>
</p>
</div>
</div>
</div>";
$total += $element["value"] * $ligne["ProduitPrix"];
$_SESSION["prix"] = $ligne["ProduitPrix"];
}
echo "<div>total : <strong>" . $total . "$</strong></div>";
echo "<div>total après taxes <strong>: " . round($total * 1.15,2) . "$</strong></div>";
}
$mysqli->close();
}
?>
<form method="POST" action="#">
<input type="submit" name="PasserCommande" value="Commandez maintenant" />
</form>
Based on the information you provided, I can only think of the following :
$_SESSION["achats"] is a array and isset($_SESSION["prix"]) is NOT(or having only 1 value)
For example, you have:
$_SESSION["achats"] = array( '1' => '1', '2' => '2');
$_SESSION["prix"] = "65"
Please provide more code, perhaps your input if this is not what you after.
I've sold the problem, I added this and it's working :
while ($element = each($_SESSION["achats"])) {
$queryTest = "SELECT ProduitPrix FROM produits WHERE ProduitID = ". $element["key"];
$res = $mysqli->query($queryTest);
while($prixCommandes = $res->fetch_assoc())
{
$queryOrderDetail = "INSERT INTO detailcommande(CommandeID, ProduitID, CommandeTotal, CommandeDate) VALUES('".$orderID."','".$element["key"]."', '".$prixCommandes["ProduitPrix"]."', CURRENT_TIMESTAMP())";
$mysqli->query($queryOrderDetail);
}
}
Thank you for trying to help me
Currently I am using a file with css and all.I have a problem as i am using php output between many html tags. The menu consist of the hard coded pages which is included with the php require_once. However, i also want to add in some pages from my database.
The Problem: The menu only shows 1 page name from my database when i have 2. It is displaying the 2nd page's name i have made. However clicking on it, it calls up the content from the 1st page.
The page name from my database is added using php output after the <ul id="menu-toc">
The page's content from my database is added at the bottom of the "The Page" section.
update: I've changed the placing of the while loop before the to after the
Pattern of css
<div class="bb-item" id="abscess">
<div class="content">
<div class="scroller">
Content
</div>
</div>
</div>
The Page
function find_condition() {
global $connection;
$query = "SELECT * ";
$query .= "FROM pages ";
$query .= "WHERE visible = 1 ";
$query .= "AND subject_id = 2 ";
$query .= "ORDER BY position ASC";
$page_set = mysqli_query($connection, $query);
confirm_query($page_set);
return $page_set;
}
$two = find_condition();
while($page = mysqli_fetch_assoc($two)) {
$pagearray = $page['menu_name'];
?>
<ul id="menu-toc" class="menu-toc">
<li class="menu-toc-current">
ABSCESS</li>
<li>APTHOUS ULCER</li>
<li>BAD BREATH</li>
<?php
$output = "<li>";
$output .= "<a href=\"";
$output .= $pagearray;
$output .= "\">";
$output .= $pagearray;
$output .= "</a></li>";
}
echo $output;
?>
</ul>
</div>
<div class="bb-custom-wrapper">
<div id="bb-bookblock" class="bb-bookblock">
<?php require_once("abscess.php"); ?>
<?php require_once("apthousulcer.php"); ?>
<?php require_once("bad breath.php"); ?>
<?php
$two= find_condition();
while($page = mysqli_fetch_assoc($two)) {
$pagearray = $page['menu_name'];
$content = $page['content'];
$output .= "<div class=\"bb-item\" id=\"";
$output .= $pagearray;
$output .= "\">";
$output .= "<div class=\"content\">";
$output .= "<div class=\"scroller\">";
$output .= "<h2>";
$output .= $pagearray;
$output .= "</h2>";
$output .= $content;
$output .= "</div>";
$output .= "</div>";
$output .= "</div>";
}
echo $output;
?>
You're starting a new <ul> each time through the while loop. You should just do that once, before the loop. You're also reinitializing $output each time through the loop, but not printing it in the loop. So you're just printing the last assignment of output after the loop is done.
$two = find_condition();
?>
<ul id="menu-toc" class="menu-toc">
<li class="menu-toc-current">
ABSCESS</li>
<li>APTHOUS ULCER</li>
<li>BAD BREATH</li>
<?php
while($page = mysqli_fetch_assoc($two)) {
$pagearray = $page['menu_name'];
?>
<?php
$output = "<li>";
$output .= "<a href=\"";
$output .= $pagearray;
$output .= "\">";
$output .= $pagearray;
$output .= "</a></li>";
echo $output;
}
?>