I'm trying to build a members-system in which you can view certain values from a database.
It worked, so that was great, but I'm having a problem now because I'm using a NULL value on 'age'.
When viewing a profile page, it looks like this:
$id = $_GET["id"];
$result = mysql_query("SELECT * FROM membersfromsite WHERE `idofmember`=$_GET[id]");
$row = mysql_fetch_array($result);
echo "<b>" . $row['userusername'] . "</b>: </p>"; ?>
<?php
$id = $_GET["id"];
$result = mysql_query("SELECT * FROM membersfromsite WHERE `idofmember`=$_GET[id]");
$noage = mysql_query("SELECT ISNULL([age]) FROM membersfromsite WHERE `idofmember`=$_GET[id]");
while ($row = mysql_fetch_array($result))
{
echo "<p class='middle'>id-number: " . $row['idofmember'] . "<br>";
echo "Username: " . $row['userusername'] . "<br>";
if ($noage)
{
echo "Age not specified";
}
else
{
echo "Age: " .$row['age'] ;
}
}
I have tried all kinds of other things, but the problem which I 'm having is that it either returns 'Age not specified' on every userpage or the age on every userpage, including the pages with a NULL value, which makes it look like:
Age:
The code which you can see above returns the age on every page, including the pages with an age which is set to NULL. What I don't understand is if I change the code to this:
$noage = mysql_query("SELECT * FROM membersfromsite WHERE `idofmember`=$_GET[id] AND age IS NULL");
it simply doesn't work. Since I'm using IS NULL instead of = NULL I don't really see why this shouldn't work, but I guess it has to do with the IF which is inside the 'while' thing, I don't really see in what other way I could fix this though...
I'm having an idea what the problem is, because I think that there is already a MyQS, Query done with Results and $noage is maybe ignored because of this, but I don't know how to solve this.
You don't need to do a whole separate $noage query.
Just do:
if(!$row['age'])
{
echo "Age not specified";
}
else
{
echo "Age: " .$row['age'] ;
}
Instead of if($noage) use if(!$row['age']) and skip the second query.
The other reason your code does not work is that the second query returns an array with something like array('expr1' => 0) which is not false. You only get a false result if nothing is found.
The reason why = NULL does not work? There are books written about it, it is just as it is.
Rather than relying on MySQL to tell us if no age was found or not, we can programatically determine whether the age value is Null right in PHP.
Here is an example:
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM membersfromsite WHERE `idofmember` = '" . mysql_real_escape_string($id) . "'");
while($row = mysql_fetch_array($result)) {
echo '<p class='middle'>id-number: ' . $row['idofmember'] . '<br>';
echo 'Username: ' . $row['userusername'] . '<br>';
if($row['age'] === Null) {
echo "Age not specified";
} else {
echo "Age: " .$row['age'] ;
}
}
Related
Thanks in advance to those who will have taken time to look at my issue. I fetch results from a table that describe activities of a contractor. There are a large number of True/False fields and I seek only to display those that are true. I create a field_name => field_type array and parse my display accordingly. (apologies for the large code snippet.)
$result = $mysqli->query($visitsSQL);
if ( $result->num_rows == 0 ){ // Visit records don't exist
$_SESSION['message'] = "Cannot find any unpaid visits";
header("location: error.php");
}
else { // unpaid visits exist
$fields= array();
while ($finfo = mysqli_fetch_field($result)){
$fields [$finfo->name]= $finfo->type ; //this array holds field names -> field types
} //finish fetching keys and types
echo "<br>";
echo "<br>Begin visit records<br>";
echo "<div class='review_row'> </div>"; //this puts a thin line to separate visits
while ($visit = $result->fetch_assoc()) { //here's where each visit is compiled and sent to screen
echo "<div class='review_row'>"; //this puts a thin line on the bottom to separate visits
foreach ($fields as $k => $v) {
$field_name = $k;
$field_type = $v;
$field_data = $visit[$field_name];
switch ($field_type) {
case 1: //The field is a True / False field
if ($field_data ==1){ //show the field only if the value is set to True
echo "I am a YES/NO field called " . $field_name . " <br>"; //This line is a test
echo "<span style='color: #009999;> - " . $field_name . "</span><br>";
}
break;
case 4: //The field is a double numeric
if ($field_data != null) { //show the field only if the value is set to True
echo "<span style='color: #b38f00';>" . $field_name . "</span> " . $field_data . "<br>";
}
break;
case 253: //A text field
if ($field_data != null) {
echo "<span style='color: #b38f00';>" . $field_name . "</span> " . $field_data . "<br>";
}
break;
case 254: //a Datetime field
if ($field_data != null) {
echo "<span style='color: #b38f00';>" . $field_name . "</span> " . $field_data . "<br>";
}
break;
default: { //field type is not represented above
// do nothing so far I take care of each field type above
}
} //end of switch
} //end of foreach
} //end of while loop for the query results
echo "</div>";
} // end of if / else that determine if there are records to display
The strange results occur in the "switch" statement where "case 1". My current test record has 7 YES/NO fields whose values are all set to 1. They are
Prepared evening meal
Cleaned up evening meal dishes
Shopped for groceries
Washed and folded clothes
Washed bedding
Vacuumed carpets
Swept kitchen floor
I should get two "echo"s for each "field_type = 1": (1) my test echo and (2) what I eventually want to display, but for some reason they display alternately - see image below. I've fought with this for two days, trying if/then parsing as well, but I come up with this "every-second-one" type of result.
screenshot of output from query
Thanks for any thoughts or direction.
I have found the problem & corrected it. It had to do with the "span..." tags. I replaced the inline "style=..." with a class. I set the the color within the class then removed settings with an "class: after" section.
I have already asked this related question: https://webmasters.stackexchange.com/questions/116055/using-mysql-database-data-directly-into-generating-articles-for-my-website-new/116056?noredirect=1#comment154341_116056
At this point, I'm starting to understand the code syntax and project structure a little better.
But I have made my database using MySQL console. it only has a few entries so far, I wanted to try to adapt the code in Zach's example, but here is the problem I have:
The problem is, I am unsure how to get the reference to my database object? In the code sample from Zach there is variable $db, I guess this is where i need to keep a reference to my own actual database.
Here is the psuedo-code (maybe) from Zach, note: he always said to me not to copy-paste it, but I'm just trying to see how I can use it in my project.
<?php
$SQL_Query = "SELECT * FROM your_table";
$SQL_Run = mysqli_query($db, $SQL_Query);
while ($row = mysqli_fetch_assoc($SQL_Run)) {
echo
"<section class='wrapper style1'>
<div class='inner'>
<header class='align-center'>
<h2>" . $row['imageurl'] . "</h2>
<img src='" . $row['title'] . "'>
<p>" . $row['description'] . "</p>
</header>
</div>
</section>";
}
?>
So my question simply at moment is: How to create the reference $db?
Your answer is the correct way to establish a connection. I want to point out that there are two ways of writing that statement. The version you found online is one way, but from our previous conversation, you can write it like this:
<?php
// Establish how to log in
$servername = "127.0.0.1";
$username = "root";
$password = "yourpasswordhere";
$dbname = "yourdatabasenamehere";
// create the database connection
$db = new mysqli($servername, $username, $password, $dbname);
// if it fails, kill the site.
if (mysqli_connect_error($db)) {
die("Connection failed: " . mysqli_connect_error($db));
}
// your first query to grab all the article data
$SQL_Query = "SELECT * FROM your_table";
// run the query
$SQL_Run = mysqli_query($db, $SQL_Query);
// while data exists (it makes sure that you have post data, otherwise nothing shows up)
while ($row = mysqli_fetch_assoc($SQL_Run)) {
echo
"<section class='wrapper style1'>
<div class='inner'>
<header class='align-center'>
<h2>" . $row['imageurl'] . "</h2>
<img src='" . $row['title'] . "'>
<p>" . $row['description'] . "</p>
</header>
</div>
</section>";
}
// Close the connection
mysqli_close($db);
?>
You will notice that the connections are written like a function.
mysqli_num_rows($result);
instead of
$result->num_rows
Both do the same thing, just a personal preference. That should hopefully clear some things up from your first post :)
I have got further on and I think have answered my own question. I found it a bit tricky to research because I don't understand all the different terms and names of features/api/scripts/etc. But I had just to read the documentation for mysqli_connect(), I set up the code as follows and now I have pulled all the data from the database into words on my html/php files.
From here I think I can rewrite the code to first sort it by date and then can of course put the latest posts at the top of each page etc.
I can also allow the user to click 'Genre' and only view Comedy for example.
Here is the code just to get the data parsed into my index.php file:
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "yourpasswordhere";
$dbname = "yourdatabasenamehere";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, type, title FROM releases";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Type: " . $row["type"]. " - Title " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
I extended upon the above work by making the php script fetch all the entries in the database and create the previous html article I had once for each entry. In the SELECT statement I can control which types of entries are displayed (eg. For a certain category). Here was how I did it:
// make an html article based snippet (image, title, description, etc),
//once for each entry in the database table...
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "somepassword";
$dbname = "somedatabasename";
// create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// check connection
if ($conn->connect_error) {
die("connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM releases ORDER BY id DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo '<section class="wrapper style1">';
echo '<div class="inner">';
echo '<header class="align-center">';
echo '<h2>'. $row["title"] . '</h2>';
echo '<div class="image fit">';
echo '<img src='. $row["imgurl"] .'>';
echo '</div> <p> RELEASE TITLE: ' . $row["title"] . '<br /> DATE POSTED: ' . $row["postdate"] . '<br /> DESCRIPTION: ' . $row["description"] . '</p>';
echo 'DOWNLOAD LINK: '.$row["link"].' <br />';
$NfoLink = $row["nfolink"];
if ($NfoLink != 'not found' && $NfoLink != '')
{
echo 'NFO LINK/MORE DOWNLOADS: '.$row["nfolink"].'';
}
echo '</header>';
echo '</div>';
echo '</section>';
}
}
else
{
echo "0 results";
}
$conn->close();
?>
My url type is like "http://localhost/boardgame/profile/Duncan/" the last word is the user name...
I just try to get some data from database and I need a user name to do this. I tried to get it from page URL but it doesn't work. Where did I go wrong? What has to be done? I'll be greateful if anybody can help...
<?php
$actual_link = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
//echo $actual_link;
$rest = substr($actual_link, 35, -1);
echo $rest;
$link = mysqli_connect("localhost", "root", "", "bgt");
if (mysqli_connect_error()) {
die ("Veritabanı bağlantısında hata var");
} if (($rest) !="") {
if (get_current_user_id($link) == '0') {
echo "<p>Kullanıcının koleksiyonunu görebilmek için giriş yapmanız
gerekiyor.</p>";
} else {
$query = "SELECT TITLE FROM wp_user_collections WHERE `user_name` =
'".mysqli_real_escape_string($link, $rest)."'";
echo "<div><h1>'".mysqli_real_escape_string($link, $rest)."'in
Koleksiyonu</h1><div>";
if($result = mysqli_query($link, $query)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>Oyun Adı</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>'" . $row['TITLE'] . "'</td>";
echo "</tr>";
}
echo "</table></div>";
}
}
}
} else {
echo "Kullanıcının koleksiyonunu görebilmek için <a
href='http://localhost/boardgame/profile/'".mysqli_real_escape_string($link,
$rest)."'>tıklayınız</a>";
}
?>
Here is the solution I have thought...using array then extracting the last element (or second last since there is a trailing '/' slash which is a delimiter)
$uri="http://localhost/boardgame/profile/Duncan/";
$uriParts=explode('/', $uri); //converts the uri string into an array of words separated by forward slash
$name=$uriParts[sizeOf($uriParts)-1-1]; //the user name comes from 2nd last item as the last item is empty
echo $name;
I could suggest you use Regular Expression to extract the user name, however I'm not well versed with it yet.
I host at hostgator and have about 30 mysql databases (all different websites that sit on the same server). For the last year.. no problems and suddenly, the last 2 days, I've seen 5 - 10 of these databases marked as 'crashed' and they return no results... so my websites display no info. I have to run a "repair table mytable" to fix these and then they work great again.
Instead of logging in to go through the databases 1 by 1 every morning, is there a way I could setup a php page to connect to all 30 databases and run a simple select statement.. and if it works, return
"database db1 is working"
"database db2 is working"
and then when not working, return
"no reply from db3"
....or something similar?
Thanks!
There's no reason you couldn't have a script that lists all of your databasenames and login credentials, and try to connect in turn to each:
$logins = array(
array('dbname' => 'blah', 'user' => 'username1', 'password' => 'password1'),
array('dbname' => 'yuck', ....)
...
);
$failures = array();
foreach ($logins as $login) {
$con = mysql_connect('servername', $login['user'], $login['password']);
if (!$con) {
$failures[] = $login['dbname'] . " failed with " . mysql_error();
continue;
}
$result = mysql_select_db($login['dbname']);
if (!$result) {
$failures[] = "Failed to select " . $login['dbname'] . ": " . mysql_error();
continue;
}
$result = mysql_query("SELECT something FROM sometable");
if (!$result) {
$failures[] = "Faile to select from " . $login['dbname'] . ": " . mysql_error();
continue;
}
if (mysql_num_rows($result) != $some_expected_value) {
$failures[] = "Got incorrect rowcount " . mysql_num_rows($result) . " on " . $login['dbname'];
}
etc....
mysql_close();
}
if (count($failures) > 0) {
echo "Failures found: "
print_r($failures);
}
You should be able to do something like the following:
<?php
//connect to database
mysql_connect('database','user','password');
//get all database names
$result = mysql_query("show databases;");
//iterate over all databases returned from 'show databases' query
while($row = mysql_fetch_array($result)) {
//DB name is returned in the result set's first element. select that DB
mysql_selectdb($row[0]);
//get all tables in the database
$query = "show tables;";
$result2 = mysql_query($query);
echo "Query: (".$row[0].")$query\n";
echo mysql_error();
//iterate over all tables in the current database
while($row2 = mysql_fetch_array($result2)) {
//the first element of the returned array will always be the table name, so:
$query = "select * from ".$row2[0]." where 1=1;";
$result3 = mysql_query($query);
echo "Query:\t(".$row[0].'/'.$row2[0].")$query\n";
//If mysql_query returns false (i.e., $result3 is false), that means that
// the table is damaged
if(!$result3) {
echo "***Error on table '".$row2[0]."' *** ... Fixing...";
//So, we repair the table
mysql_query("repair table ".$row2[0].";");
}
}
}
?>
I want to convert my sql data to csv files while clicking on a button. The code fragments I found for sql to CSV conversion were in PHP, and I'm trying to convert it to CakePHP since I'm working in CakePHP.
Here is the PHP code I'm tring to convert:
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field']."; ";
$i++;
}
}
$csv_output .= "\n";
$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j]."; ";
}
$csv_output .= "\n";
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
SOLUTION
Function in the Controller:
function exporttocsv()
{
$this->set('headers',$this->Result->find('all',array('fields'=>'Result.label')));
$this->set('values',$this->Result->find('all',array('fields'=>'Result.value')));
}
exporttocsv.ctp file:
<?php
foreach($headers as $header):
$csv_output .=$header['Result']['label'].", ";
endforeach;
$csv_output .="\n";
if(!empty($values)){
foreach($values as $value):
$csv_output .=$value['Result']['value'].", ";
endforeach;
$csv_output .="\n";
}
else{
echo "There is no data to export.";
}
$filename = "export_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
?>
First of all, you don't do queries and output in the same file in Cake. You query the data as usual in the Controller, $this->set() the result to the view, and in the view you do something like this:
foreach ($results as $result) {
echo join(', ', $result['COLUMNS']);
echo "\n";
}
Outputs something like this:
value, varchar(25), NO, , ,
submitter, int(11), NO, , ,
...
Since Cake automatically wraps a layout around your view, you'll have to set the layout to something different, like 'ajax' (which is simply an empty layout).
deceze is correct about outputting the results from the view file. You'll just need to set some headers so that it appears as a file download on the client side. You can simply put these 2 calls in the top of your view:
header("Content-type:application/vnd.ms-excel");
header("Content-disposition:attachment;filename=\"{$filename}\"" );
If you plan on doing csv downloads in more than one place in your application, I'd recommend this helper:
http://bakery.cakephp.org/articles/view/csv-helper-php5
I use it and it works well.