I need to use multiple queries and send them out as well formed xml for as3 purposes.
When I use only one query everything works fine.
Problem starts when multi-query operates.
Right now when //XML header is hidden I get a structure printed on screen and it looks good.
But when header goes enabled, nothing works!
Please take a look at my code:
<?php
$dbHost = "localhost";
$dbUser = "root";
$dbPass = "";
$dbName = "test";
$dbTable = "pizzaroma";
$mysqli = mysqli_connect($dbHost, $dbUser, $dbPass, $dbName);
if ($mysqli->connect_errno)
echo "la conection ha fallado: ".$mysqli->connect_errno;
$query = "SELECT * FROM ".$dbTable." WHERE cat='pizza' AND act='1' ORDER BY ID ASC; ";
$query .= "SELECT * FROM ".$dbTable." WHERE cat='pasta' AND act='1' ORDER BY ID ASC; ";
if ($mysqli->multi_query($query)) {
// header("Content-type: text/xml");
echo "<?xml version='1.0' encoding='UTF-8'?>";
echo "<pics>";
do {
echo "<theme name='temporaly'>";
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_assoc()) {
echo "<pic name='".$row['NAME']."' desc='".$row['DESCES']."' price='".$row['PRICE']."'/>";
echo "</pic>";
}
$result->free();
}
echo "</theme>";
if ($mysqli->more_results()) {
}
}
while ($mysqli->next_result());
echo "</pics>";
}
$mysqli->close();
?>
earlier i were using "echo",.. now instead ive put "printf" there,.. but only some lines, i am not sure if that was the reason.. but now works. it was throwing me the
"Strict Standards: mysqli_next_result(): There is no next result set. Please, call mysqli_more_results()/mysqli::more_results() to check whether to call this function/method" so looking for help i have found this line there :
do{} while(mysqli_more_results($db) && mysqli_next_result($db));
that solved the problem for xml error.
<?php
$dbHost = "localhost";
$dbUser = "root";
$dbPass = "";
$dbName = "test";
$dbTable = "pizzaroma";
$mysqli = mysqli_connect($dbHost, $dbUser, $dbPass, $dbName);
if ($mysqli->connect_errno)
echo "la conection ha fallado: ".$mysqli->connect_errno;
$query = "SELECT * FROM ".$dbTable." WHERE cat='pizza' AND act='1' ORDER BY ID ASC; ";
$query .= "SELECT * FROM ".$dbTable." WHERE cat='pasta' AND act='1' ORDER BY ID ASC; ";
$query .= "SELECT * FROM ".$dbTable." WHERE cat='carne' AND act='1' ORDER BY ID ASC; ";
if ($mysqli->multi_query($query)) {
header("Content-type: text/xml");
printf( "<?xml version='1.0' encoding='UTF-8'?>");
printf( "<pics>");
do {
printf( "<theme name='temporaly'>");
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_assoc()) {
echo "<pic name='".$row['NAME']."'/>";
}
$result->free();
}
echo "</theme>";
}
while (mysqli_more_results($mysqli) && mysqli_next_result($mysqli));
echo "</pics>";
}
$mysqli->close();
?>
later on i´ve had to serialize the xml output it was easy :D
>> $i=1; and ... do {printf( "<theme name='".$i++."'>");
but now ,.. how do I associate output serialIDs to elements from array that contains category names. something like...
if name="1" then name="firtsArrayChild"
any idea?
but i think that is another song for another question out there! thanks
Related
I need help with some code. I want to select data from mySQL to a graph on my web page.
The data must be from the current logged in user, and when I select data to a card it works fine, but when I select it to a graph the graph disappears.
I'm using this code for the cards, and it works fine:
$sql = "SELECT energyexpenditure FROM energy4project WHERE user_id = '{$_SESSION["user_id"]}' ORDER BY time_stamp DESC LIMIT 1;";
This is the code for my current graph that don't show data based on logged in user:
<?php
header('Content-Type: application/json');
$host = "localhost";
$user = "`blabla";
$pwd = "blabla";
$db = "blabla";
$conn = new mysqli($host, $user, $pwd, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT energyexpenditure, time_stamp FROM energy4project ORDER BY time_stamp DESC LIMIT 7;";
$result = $conn->query($sql);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
mysqli_close($conn);
echo json_encode($data);
?>
When I implement the code from the cards in the graph code it doesn't work.
Why does the SELECT WHERE user = '{$_SESSION["user_id"]} not work in the graphs?
If I understood good your Mysql query return an empty result. Try to modify your code as follows:
if(!$result = $conn->query($sql)) {
echo "query error.";
die();
}
$data = array();
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$data[] = $row;
}
/* free result set */
$result->free();
/* close connection */
$conn->close();
//uncomment the below line if you want to check de result of your mysql query because it seems be good.
//var_dump($data); die(); echo "<pre>";
echo json_encode($data);
So if you don't have any mysql error, verify your database name, table name are correctly and if it has data in your table.
Reference: https://www.php.net/manual/en/mysqli-result.fetch-array.php
Regards
I am trying to list the ids associated with usernames from a database using an XML file that contains the corresponding usernames.
I think this might have something to do with $conn not being a global variable
Is that right?
I am using the following code:
<?php //idlister.php
require 'connectDB.php';
$xml=simplexml_load_file("names.xml") or die("Error:
Cannot create object");
foreach($xml->book as $book)
{
$username = (string)$book->username;
$sql = "SELECT `id`
FROM `directory`
WHERE `UserName` = '$username'
LIMIT 0 , 30";
if ($result = $conn->query($sql)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row["id"]."<br />";
}
/* free result set */
$result->free();
}
}
$conn->close();
?>
When I run the above code, the browser keeps working until it gets a 502 Gateway error.
I tested the same code above, replacing '$username' with 'Bill' (a name in the database), and got the same 502 Gateway error.
But when I took the $result = $conn->query($sql) line out of the for each loop, I got the results I was looking for:
<?php //idlister.php
require 'connectDB.php';
$xml=simplexml_load_file("names.xml") or die("Error:
Cannot create object");
$username = (string)$book->username;
$sql = "SELECT `id`
FROM `directory`
WHERE `UserName` = 'Bill'
LIMIT 0 , 30";
if ($result = $conn->query($sql)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row["id"]."<br />";
}
/* free result set */
$result->free();
}
$conn->close();
?>
// Printed "20", which is Bill's id
How do I get results from within the foreach loop, or how do I get the names from the XML file to search the database outside of the foreach loop?
XML Sample:
<response>
<book>
<username>Sarah</username>
<gender>f</gender>
<age>23</age>
</book>
<book>
<username>Jonathan</username>
<gender>m</gender>
<age>33</age>
</book>
<book>
<username>Demonte</username>
<gender>m</gender>
<age>18</age>
</book>
</response>
Connection file:
<?php //connectDB.php
$servername = "localhost";
$username = "username";
$password = "password";
$database = "Directory";
// Create connection to Directory
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection to the Directory failed: " . $conn->connect_error);
}
echo "<h2>Directory Connection Successful</h2>";
?>
I need some help and I can't figure it out,i tried searching the internet but I found nothing
So I'm using this code from w3schools
<?php
$servername = "localhost"; //Obviously this are set to my parameters
$username = "username"; //Obviously this are set to my parameters
$password = "password"; //Obviously this are set to my parameters
$dbname = "myDB"; //Obviously this are set to my parameters
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM People";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//Some code goes here
}
} else {
echo "0 results";
}
$conn->close();
?>
How can I modify this code to echo certain items only?
EXAMPLE
I have 10 items in talbe People (Table people contains id,age,name,gender)
I want to echo out 3 out of 10 People by using their ID which are 1 trough 10
I know i can use this AND id IN(1, 5, 9)"; This just echoes them out 1 after another
Is there a way to echo out id 1 goes here , id 5 goes here and than id 9 goes there like in 3 different places with 3 different codes or something? is this even possible?
You could use:
class people
{
public function people()
{
$sql = $this->conn->prepare("SELECT * FROM `people`");
$sql->execute();
$result = $sql->fetch(PDO::FETCH_OBJ);
return $result;
}
}
then when you want certain information you could simply use in say index.php:
$fetch = new people();
$info = $fetch->people();
you can then run simple echo's such as $info->name or $info->id etc etc..
Depending on how you're searching for the user you could just add
WHERE `userid` = :id
$sql->bindParam(':id', $userid);
and add $userid into the people($userid)
But this will vary depending on how you're pulling out specific users.
use this code
<?php
//using PDO
try
{
$conn = new PDO('mysql:dbhost=myhost;dbname=mydbname;', 'user','pass');
}
catch (PDOException $e)
{
echo $e->getMessage();
}
$getId = $conn->query("
SELECT * FROM users
WHERE id = 1
AND id = 5
AND id = 9
");
while ($ids = $getId->fetch(PDO::FETCH_OBJ)
{
echo $getId->id . '<br>';
}
I am using this same code `
php $postId = 41;
<!-- hidden items and variables. Elements that will not be revealed !-->
<span id="gameLength"><?php
// MySQL connect configuration
$dbname="my_db";
$host="localhost";
$user="guessthe";
$dbh=mysql_connect ($host,$user,"correctPassword?") or die ('I cannot connect to the database because: ' . mysql_error(). '');
mysql_select_db ("$dbname") or die('I cannot select the database because: ' . mysql_error());
$sql="SELECT * FROM games WHERE postId = $postId";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
$gameId = $rows['id'];
$game100s = $rows['game100s'];
$gamesPlayedAllTime = $rows['gamesPlayed'];
$gamesPointsAllTime = $rows['gameScore'];
$gameLength = $rows['gameLength']; // get number of questions
$gameScore = $rows['gameScore'];
$gameType = $rows['gameType'];
$gametitle = $rows['gameSubTitle'];
echo $gameLength;
There is a value in the gameLength row! I can't get this code to pull any of the rows! Any idea what i'm doing wrong?
You're using MySQL, which is depcirated - and will be phased out. You should use MySQLi or PDO instead. Also, your $postId is defined outside a PHP-tag? Might just be a copy/paste mistake? Anyway, you can try the code below, which is in MySQLi:
<?php
$postId = 41;
?>
<!-- hidden items and variables. Elements that will not be revealed !-->
<span id="gameLength"><?php
// MySQL connect configuration
$dbname = "my_db";
$host = "localhost";
$user = "guessthe";
// Connecting to the database
$mysqli = new mysqli($host, $user, "correctPassword?", $dbname);
if ($mysqli->connect_errno) {
// If we are here, the connection failed
echo "Failed to connect to MySQL: (".$mysqli->connect_errno.") ".$mysqli->connect_error;
}
$sql ="SELECT * FROM games WHERE postId = $postId";
if ($result = $mysqli->query($sql)) {
// If the query was sucsessfull, we can get the rows
while ($row = $result->fetch_assoc()) {
$gameId = $row['id'];
$game100s = $row['game100s'];
$gamesPlayedAllTime = $row['gamesPlayed'];
$gamesPointsAllTime = $row['gameScore'];
$gameLength = $row['gameLength']; // get number of questions
$gameScore = $row['gameScore'];
$gameType = $row['gameType'];
$gametitle = $row['gameSubTitle'];
}
} else {
// If the query failed, do something here
}
echo $gameLength;
?>
I see some people commenting that you need to put the $postId variable inside quotes in the query, but when using double-quotes (") variables will be posted, so it's not really needed. Also note that things are case-sensitive, so if your results doesn't show, check for spelling-mistakes.
There are many errors in your code
Try this...
<?php
$postId = 41;
?>
<!-- hidden items and variables. Elements that will not be revealed !-->
<span id="gameLength">
<?php
// MySQL connect configuration
$host = "localhost";
$dbname = "my_db";
$user = "username";
$password = "password";
$dbh = mysql_connect ($host,$user,$password) or die ('I cannot connect to the database because: ' . mysql_error() . '');
mysql_select_db($dbname, $dbh) or die('I cannot select the database because: ' . mysql_error());
$sql = "SELECT * FROM games WHERE postId='$postId'";
$result = mysql_query($sql);
while($rows = mysql_fetch_array($result)){
$gameId = $rows['id'];
$game100s = $rows['game100s'];
$gamesPlayedAllTime = $rows['gamesPlayed'];
$gamesPointsAllTime = $rows['gameScore'];
$gameLength = $rows['gameLength']; // get number of questions
$gameScore = $rows['gameScore'];
$gameType = $rows['gameType'];
$gametitle = $rows['gameSubTitle'];
echo $gameLength;
}
?>
You need to fix this is your code and that should fix the error.
$sql="SELECT * FROM games WHERE postId ='".$postId."' ";
If you want all the records you can use a while loop. Here is some pseudo code.
while($row = mysql_fect_assoc($query)){
echo $row["THE THING YOU WANT"];
...
}
When i run the following code it will return 100 users record from a table but when i increase the value of LIMIT from 100 to a greater number like 5000 then it will not return anything.i have total 6000 records in table. So how can i access different number of records like 2000, 3000 or even all 6000 records? kindly Guide what's wrong!
<?php
$db = mysql_connect("localhost","root","");
if (!$db) {
die('Could not connect to db: ' . mysql_error());}
mysql_select_db("distributedsms",$db);
$result = mysql_query("select * from users LIMIT 100", $db);
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['user no'] = $row['sno'];
$row_array['mnc'] = $row['mnc'];
$row_array['mcc'] = $row['mcc'];
$row_array['lac'] = $row['lac'];
$row_array['cell id'] = $row['cell id'];
$row_array['lat'] = $row['lat'];
$row_array['lng'] = $row['lng'];
$row_array['address'] = $row['address'];//push the values in the array
array_push($json_response,$row_array);
$users = $json_response;}
$fp = fopen('users_data.json', 'w+');
fwrite($fp, json_encode($json_response));
fclose($fp);
echo json_encode($json_response);
?>
First, enable error reporting in your INI or Script:
<?php error_reporting(E_ALL);
ini_set('display_errors', 1);
This will help you if there is any error/warning in case of low memory allocation or similar.
To fetch all records, you shouldn't use LIMIT, remove LIMIT from your SQL.
i.e. select * from users
You should not use mysql_connect as it is deprecated. Use mysqli_connect instead. Also, I don't think you need to iterate so much, just choose what you want in your select statement.
UPDATE: another factor on why this might be happening can also be the returned information from the database, if you have apostrophes ' in your strings and you try to use json_encode, it will break, you would need to addslashes first.
Try the following, change your LIMIT as you wish, and let me know if you still have those errors:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT sno,mnc,mcc,lac,cell_id,lat,lng,address FROM users LIMIT 100";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$response = array();
while ($row = $result->fetch_assoc()) {
foreach($row as $k => $str){
$row[$k] = addslashes($str);
}
array_push($response, $row);
}
echo json_encode($response);
} else {
echo "0 results";
}
$conn->close();
?>