I've been trying to execute a multiple query, so I've searched for a better approach on how to do this and I've read this mysqli_multi_query in php.
I tried it on my own to see the results, but it keeps on giving me error. Here's the code:
$studid = $_GET['stud_id'];
$classcode = $_GET['class'];
$conn = new MySQLi($host, $username, $password, $dbname) or die('Can not connect to database');
$sql = "SELECT * FROM tbl_students WHERE stud_id = '".$studid."'";
$sql.= "SELECT * FROM tbl_classes WHERE class_code = '".$classcode."'";
if (mysqli_multi_query($conn, $sql)) {
do {
/* store first result set */
if ($result = mysqli_store_result($conn)) {
while ($row = mysqli_fetch_row($result)) {
$studname = $row[3].", ".$row[1];
}
mysqli_free_result($result);
}
/* print divider */
if (mysqli_more_results($conn)) {
printf("-----------------\n");
$studname = $row['fname'];
}
} while (mysqli_more_results($conn));
}else{ echo "error";}
$conn->close();
With the code above, it will just print error from the else statement I set. I also tried changing the second query to $sql .= "SELECT * FROM tbl_classes WHERE class_code = '".$classcode."'"; and also tried putting semicolon after the first query to tell the SQL that I'm done with the first query since I'm putting 2 strings together, but still no luck.
try this
$studid = $_GET['stud_id'];
$classcode = $_GET['class'];
$conn = new MySQLi($host, $username, $password, $dbname) or die('Can not connect to database');
$sql = "SELECT * FROM tbl_students WHERE stud_id = '$studid';";
$sql.= "SELECT * FROM tbl_classes WHERE class_code = '$classcode'";
if ($conn->multi_query($sql)) {
do {
/* store first result set */
if ($result = mysqli_store_result($conn)) {
while ($row = mysqli_fetch_row($result)) {
$studname = $row[3].", ".$row[1];
}
mysqli_free_result($result);
}
/* print divider */
if (mysqli_more_results($conn)) {
printf("-----------------\n");
$studname = $row['fname'];
}
} while (mysqli_more_results($conn));
}else{ echo "error";}
$conn->close();
Make one query instead of two :
"SELECT ts.*, tc.*
FROM tbl_students as ts, tbl_classes as tc
WHERE ts.stud_id = '$studid'
AND tc.class_code = '$classcode'"
Note : If you get redundant data then use group by.
Related
I cannot get my Mysqli queries to both work. If I comment out one function in my html, the other function is properly executed and vice versa.
function all_posts() {
require_once 'database.inc.php';
$mysqli = mysqli_connect($host, $username, $password, $database);
$query = mysqli_query($mysqli, "SELECT variable_name, post_name, post_date, post_display FROM blog_posts ORDER BY id DESC LIMIT 5");
if (!$query)
echo mysqli_error();
while ($results = mysqli_fetch_assoc($query)) {
$post_name = $results['post_name'];
$post_date = $results['post_date'];
$post_display = $results['post_display'];
$variable_name = $results['variable_name'];
echo "<a href='posts.php?post={$variable_name}'>";
echo "<div class='entry'>";
echo "<div class='entry_header'>";
echo "<h2>{$post_name}</h2>";
echo "<h3>{$post_date}</h3>";
echo "</div>";
echo "<p>{$post_display}</p>";
echo "</div>";
echo "</a>";
}
mysqli_free_result();
}
function all_sidebar_posts() {
require_once 'database.inc.php';
$mysqli = mysqli_connect($host, $username, $password, $database);
$query = mysqli_query($mysqli, "SELECT variable_name, post_name FROM blog_posts ORDER BY id DESC LIMIT 5");
while ($results = mysqli_fetch_assoc($query)) {
$post_name = $results['post_name'];
$variable_name = $results['variable_name'];
echo "<li><a href='posts.php?post=$variable_name'>$post_name</a></li>";
}
mysqli_free_result();
}
Here is the html that I am outputting to.
<ul>
<?php all_sidebar_posts(); ?>
</ul>
</div>
<div class="content_container">
<?php all_posts(); ?>
</div>
I have tried using mysqli_data_seek(); but haven't had luck. Perhaps I am not using it right? I have browsed many questions and found similar ones but I have tried them all to no avail. I am new to programming so I may be overlooking something basic. Thank you all for the help!
You are doing it wrong way.
Never mix your data manipulation code with presentation code.
First, get the posts into array:
require_once 'database.inc.php';
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect($host, $username, $password, $database);
$sql = "SELECT variable_name, post_name, post_date, post_display
FROM blog_posts ORDER BY id DESC LIMIT 5"
$result = mysqli_query($mysqli, $sql);
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
and then use this $data array to display posts any times you need, simply using foreach()
http://www.php.net/manual/en/mysqli-result.data-seek.php
Consult the manual for the usage of data_seek();
Take this example:
$Query = "SELECT * FROM Users WHERE ID='1'";
$TheQuery -> $MySQLi->query($Query);
$Results = $TheQuery->fetch_array(MYSQLI_ASSOC);
$TheQuery->data_seek(0); // Lets you re-use the query
$Count = $TheQuery->num_rows; // Gets the count
so in your case:
You should perform the procedure method:
$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
if ($result = mysqli_query($link, $query)) {
/* fetch row */
$row = mysqli_fetch_row($result);
printf ("City: %s Countrycode: %s\n", $row[0], $row[1]);
mysqli_data_seek($result, 0);
$row_cnt = mysqli_num_rows($result);
/* free result set*/
mysqli_free_result($result);
}
Using count() query with php will cause the result display in looping. How to fix this issue?
phpmyadmin has no problem showing the sum but can't apply it to php code.
$conn = mysqli_connect('localhost','root','','db');
if (!$conn) { die('db error'); };
$result = mysqli_query($conn, '
select count(*) as x from users
');
$row = mysqli_fetch_assoc($result);
echo $row['x'];
Expect result :
2
Actual output :
2222222222222222222222222222222222222222222222222222222222222222222...
I recommend you to use prepared statements.
$conn = new mysqli("localhost", "root", "", "db");
if($stmt = $conn->prepare("SELECT count(*) as x FROM users")) {
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$number = $row['x'];
}
$stmt->close();
}else{
echo "Error";
}
$conn->close();
if(isset($number)){
echo $number;
}
through a cURL connection, I can pick up data, from Json files, placed on a remote server. In particular, the codes of some products, which thanks to a foreach
foreach($data['results'] as $key=>$val){
$codici_hotel = $val['hotel_code'];
echo $codici_hotel.",";
}
I can see on video:
1074d0,19f726,1072ba,107104,183444,112438,15d8ab,1b326e,19d885,189b95,1071bf,107155,193e61,10aab2,138752,18dd7d,19d7f9,117b0d,1071b8,1398c4,107039,110851,107124,110669
Now I need to use that string to run a select on a local database, such as:
$sql = "SELECT * FROM hotels WHERE code = ('$codici_hotel')";
What is the correct sql string?
Thanks for your help
CODE UPDATE USED
$codici_hotel_arr = array();
foreach($data['results'] as $key=>$val){
$codici_hotel_arr[] = $val['hotel_code'];
}
$codici_hotel = "'".implode(",",$codici_hotel_arr)."'";
$conn2 = new mysqli($servername, $username, $password, $dbname);
if ($conn2->connect_error) {
die("Connection failed: " . $conn2->connect_error);
}
$sql2 = "SELECT name FROM hotels WHERE code IN ('$codici_hotel')";
$result2 = $conn2->query($sql2);
if ($result2->num_rows > 0) {
// output data of each row
while($row2 = $result2->fetch_assoc()) {
$nome_hotel = $row2["name"] ;
}
} else {
echo "0 results";
}
$conn2->close();
echo $nome_hotel;
You have to convert your all codes in string enclosed with '. Then use IN clause of mysql. change your code as below
$codici_hotel_arr = array();
foreach($data['results'] as $key=>$val){
$codici_hotel_arr[] = $val['hotel_code'];
}
$codici_hotel = "'".implode(",",$codici_hotel_arr)."'";
$sql = "SELECT * FROM hotels WHERE code IN ($codici_hotel)";
I'm trying to make something which will only display the name of the row which has ID 1 but I can't seem to get it to work. I can make it display all the names but I only want it to display the name of user ID 1. This is my current code but it doesn't work.
<a style="font-size: 17px; color: #ff0000;"><?php
$q = "SELECT * FROM `Team` WHERE id =1";
$result=mysqli_query($q);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
if ($row != FALSE) {
echo '<br />$row is not false.';
$name = $row['name'];
echo $name;
} else{echo "it's false :(";};
?></a>
It returns:
it's false :(
you may need the while() check on there.
Try something like:
Your database connection:
$servername = "YOUR_HOST";
$username = "YOUR_USER";
$password = "YOUR_PASSWORD";
$dbname = "YOUR_DATABASE";
$mysqli = new mysqli($servername, $username, $password, $dbname);
if ($mysqli->connect_error) {
echo "There was a slight problem, please contact your webmaster before continuing.";
exit();
}
Then your main file with displaying the row you want:
// create query
$q = "SELECT * FROM Team WHERE id = 1";
// get the records from the database
if ($result = $mysqli->query($q))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
// fetch the results
while ($row = $result->fetch_object())
{
$name = $row->name;
echo $name;
}
}
else
{
echo "No results to display!<br><hr><br>";
}
}
else
{ // show an error if there is an issue with the database query
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
mysqli_query requires first parameter should be connection string and second is the query
mysqli_query($link, "your query");
Ref: http://php.net/manual/en/mysqli.query.php
You need to add the Connection-Parameter!
$result=mysqli_query($db, $q);
instead of
$result=mysqli_query($q);
I am trying to draw data from multiple tables that have been indexed to relate to one another. I ran this query in MySQLWorkbench, and it ran successfully. However when I tried to run a PHP test, nothing showed up, not even for the first field. Here is my code:
<?php
$db = new mysqli('host', 'user', 'password', 'database');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "
SELECT
`Contact`.`firstName`,
`Contact`.`lastName`,
`ssn`.`ssn`,
`Contact`.`country`,
`Allergies`.`allergy`,
`Allergies`.`allergyType`,
`Allergies_Contact`.`allergyNotes`,
`CurrentPrescriptions`.`prescriptionName`,
`CurrentPrescriptions`.`prescribedDate`,
`BloodType`.`bloodType`
FROM
`database`.`Contact`,
`database`.`Allergies_Contact`,
`database`.`Allergies`,
`database`.`ssn`,
`database`.`CurrentPrescriptions`,
`database`.`BloodType`
WHERE
`Contact`.`contactKey` = `Allergies_Contact`.`contactKey`
AND `Allergies`.`allergiesKey` = `Allergies_Contact`.`allergiesKey`
AND `ssn`.`contactKey` = `Contact`.`contactKey`
AND `CurrentPrescriptions`.`contactKey` = `Contact`.`contactKey`
AND `BloodType`.`contactKey` = `Contact`.`contactKey`;
";
$result = $db->query($query) or die($db->error.__LINE__);
if ($result = mysqli_query($db, $query)) {
while ($row = mysqli_fetch_row($result)) {
print(row[0]);
}
mysqli_free_result($result);
}
mysqli_close($db);
?>
Please tell me what I am doing wrong here, because from what I can see its formatted correctly.
Several things:
1.- You have two query sentences, change:
$result = $db->query($query) or die($db->error.__LINE__);
if ($result = mysqli_query($db, $query)) {
With this
$result = $db->query($query) or die($db->error.__LINE__);
if ($result !== false) {
2.- Yo made a mistake when trying to print the variable, change:
while ($row = mysqli_fetch_row($result)) {
print(row[0]);
}
With this
while ($row = mysqli_fetch_row($result)) {
print($row[0]); // You missed a $
}
<?php
//conection:
$link = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " . mysqli_error($link));
//consultation:
$query = "SELECT name FROM mytable" or die("Error in the consult.." . mysqli_error($link));
//execute the query.
$result = $link->query($query);
//display information:
while($row = mysqli_fetch_array($result)) {
echo $row["name"] . "<br>";
}
?>
http://php.net/manual/en/function.mysqli-connect.php