I'm trying to make this code work but I don't know why it won't. Basically I want it to display a name if the nickname column in the database is null. And if it's not null it should display the nickname. Also I'm somewhat noob so keep that in mind when responding.
$namn = mysql_query("SELECT name FROM Horseinfo WHERE name = '$somevariable'");
$nicknamn = mysql_query("SELECT nickname FROM Horseinfo WHERE name = '$somevariable'");
<? $row = mysql_fetch_array($nicknamn,$namn);
if(is_null($nicknamn)) {?>
<div style='font-size:18px; padding-bottom:3px; margin-top:0px;'>records for <? echo $row['name'];?></div>
<?} else {?>
<div style='font-size:18px; padding-bottom:3px; margin-top:0px;'>records for <? echo $row['nickname'];?></div>
<?}?>
Based on assumption I would say that your nickname column does not contain a database NULL value, rather it would be an empty string instead (this totally depends on the routine filling the Horseinfo table). You also only need one SQL query to fetch both name and nickname.
My suggestion would be to use empty() instead:
// try to use mysqli_* instead of mysql_* functions, mysqli_query() expects parameter 1 to be a database connection resource
$res = mysqli_query($connection, "SELECT name, nickname FROM Horseinfo WHERE name = '$somevariable'");
if ($res && mysqli_num_rows($res)>0) {
$row = mysqli_fetch_row($res);
$horseName= empty($row['nickname']) ? $row['name'] : $row['nickname'];
?>
<div style='font-size:18px; padding-bottom:3px; margin-top:0px;'>records for <? echo horseName;?></div>
<?php } ?>
Related
I need to display a list of results form a survey on a PHP page then export them to a CSV file. The list also acts as a summary that can be clicked thorugh to the full result.
I have all that sorted but now I need to have the CSV export by a check bx selection so that we dont need to download the entire databse each time just the ones we need.
My code so far below.
<div class="resultsList">
<h1>PEEM Results List</h1>
<a class="exportCSV" href="https://domain.com/downloadcsv.php">Export to CSV</a>
<!-- Export CSV button -->
<h3 class="resultsbydate">All results by date</h3>
<div class="resultsListHeader">
<div class="clientidTab">Agency</div>
<div class="clientidTab">Family ID</div>
<div class="clientidName">Name</div>
<div class="clientidTab">Date</div>
<div class="clientidTab"></div>
</div>
<div class="entriesListMain">
<?php
$connection = mysql_connect("localhost", "username", "password"); // Establishing Connection with Server
$db = mysql_select_db("database_name", $connection); // Selecting Database
//MySQL Query to read data
$query = mysql_query("select * from results ORDER BY peemdate DESC", $connection);
while ($row = mysql_fetch_array($query)) {
echo "<div><input type=\"checkbox\" name=\"xport\" value=\"export\"><span>{$row['client_id']}</span> <span>{$row['family_id']}</span> <span>{$row['firstname']} {$row['lastname']}</span> <span>".date("d F Y", strtotime($row['peemdate']))."</span>";
echo "<span><a class=\"parents-button\" href=\"peem-parent-repsonses.php?id={$row['survey_id']}\"><strong>Parent’s Review</strong></a></span>";
echo "<span><strong>View Results</strong></span>";
echo "</div>";
}
?>
</div>
</div>
<?php
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query1 = mysql_query("select * from results where survey_id=$id", $connection);
while ($row1 = mysql_fetch_array($query1)) {
?>
<?php
}
}
?>
<?php
mysql_close($connection); // Closing Connection with Server
?>
And the downloadcsv.php
<?php
$conn = mysql_connect("localhost","username","password");
mysql_select_db("databasename",$conn);
$filename = "peem_results.csv";
$fp = fopen('php://output', 'w');
$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='realwell_peemfinal' AND TABLE_NAME='results'";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
$header[] = $row[0];
}
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
fputcsv($fp, $header);
$query = "SELECT * FROM results";
$result = mysql_query($query);
while($row = mysql_fetch_row($result)) {
fputcsv($fp, $row);
}
exit;
?>
Any help with this would be great, cheers
Updated with a screenshot of what I am trying to achieve
The initial result set needs to be wrapped in a form which POST to the next page.
The Checkbox must send an array of ids to the export script.
<input type='checkbox' name='xport[]' value='ID_OF_THE_ROW_HERE'>
The [ ] after xport means that $_POST['xport'] will be an array of values.
The export page can collapse that array of ids into a comma separated string and to be used the query:
SELECT * FROM results WHERE id IN (4,7,11,30)
<form method="POST" action="downloadcsv.php">
<h1>PEEM Results List</h1>
<a class="exportCSV" href="https://domain.com/downloadcsv.php">Export to CSV</a>
<!-- Export CSV button -->
<h3 class="resultsbydate">All results by date</h3>
<div class="resultsListHeader">
<div class="clientidTab">Agency</div>
<div class="clientidTab">Family ID</div>
<div class="clientidName">Name</div>
<div class="clientidTab">Date</div>
<div class="clientidTab"></div>
</div>
<div class="entriesListMain">
<?php
$connection = mysql_connect("localhost", "username", "password"); // Establishing Connection with Server
$db = mysql_select_db("database_name", $connection); // Selecting Database
//MySQL Query to read data
$query = mysql_query("select * from results ORDER BY peemdate DESC", $connection);
while ($row = mysql_fetch_array($query)) {
echo "<div><input type='checkbox' name='xport[]' value='{$row['client_id']}'><span>{$row['client_id']}</span> <span>{$row['family_id']}</span> <span>{$row['firstname']} {$row['lastname']}</span> <span>".date("d F Y", strtotime($row['peemdate']))."</span>";
echo "<span><a class=\"parents-button\" href=\"peem-parent-repsonses.php?id={$row['survey_id']}\"><strong>Parent’s Review</strong></a></span>";
echo "<span><strong>View Results</strong></span>";
echo "</div>";
}
?>
</div>
</form>
Change $row['client_id'] to the correct value
Then in the export script:
<?php
/*
Expecting $_POST['xport'] array of row ids
*/
if( !isset($_POST['xport']) OR !is_array($_POST['xport']) ) {
exit('No rows selected for export');
}
$conn = mysql_connect("localhost","username","password");
mysql_select_db("databasename",$conn);
$filename = "peem_results.csv";
$fp = fopen('php://output', 'w');
$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='realwell_peemfinal' AND TABLE_NAME='results'";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
$header[] = $row[0];
}
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
fputcsv($fp, $header);
//Cast all ids to integer
$ids = $_POST['xport'];
array_walk($ids, function(&$value, $key) {
$value = (int)$value;
});
$ids = implode(', ', $ids);
$query = "SELECT * FROM results WHERE id IN ($ids)";
$result = mysql_query($query);
while($row = mysql_fetch_row($result)) {
fputcsv($fp, $row);
}
exit;
?>
So if I'm getting this correctly, you just need to be able to check checkboxes to select the databses ($rows) you want to insert into the csv file....
Every checkbox that you checked will be in the $_POST variable, so:
1st you make an array with all the names of checkbox options (databases), for example
$all_db = ['database1', 'database2', 'database3'];
2nd you loop through each of the values in $all_db and check if they exist in the $_POST array, if they do, then you can export the row
foreach( $all_db as $db_check ) {
if ( array_key_exists( $db_check, $_POST ) {
// EXPORT TO CSV
}
}
Don't forget ! This means the "name" attribute of the checkbox should be the name of the database.
If you don't want to have a static list of databases (i.e. there is a possibillity of them having different names in the future / there will be moreor maybe less etc then let me know i can edit my answer if needed :) )
( If you use the $_GET variable, then you can do the same thing just change $_POST to $_GET)
Know though that $_GET comes over as a bit amateuristic for the enduser if he gets a thousand variables in his URL,
$_POST is often a better alternative since it is hidden and cleaner for the enduser...
EDIT: UPDATING ANSWER (SEE COMMENT)
So basically you need people to be able to choose what rows they export from you dB...
First of all this means we need a unique ID for each row,
This can either be a column used solely for that (i.e. ID column with auto increment and unique attribute)
Or this can be a column you already have, just make sure it's a unique column so we don't get dupliate values (you'll see why below)
Then we give the value of this unique ID column to the checkbox's "name" attribute, and using jquery / php we append / prepend a static string...
For example, using your family ID:
"rownumber_" + $family_ID
This gets us (again using your example) :
$_POST[] = ['rownumber_123456' => 1, 'rownumber_0000000' => 1, .....]
So then in your PHP file you just do the following to add the correct lines to your CSV:
while($row = mysql_fetch_row($result)) {
if ( array_key_exists($row['your_row_id'], $_POST) {
fputcsv($fp, $row);
}
}
-- Again using your example with family_ID : --
while($row = mysql_fetch_row($result)) {
if ( array_key_exists($row['family_ID'], $_POST) {
fputcsv($fp, $row);
}
}
EDIT: Updating answer for comment no.2
So little sidenote if you are going to loop through html using php
(i.e. loop trhough db rows and print them out in an orderly fashion)
Then you propably want to use the ":" variants of the loops,
While() :
for() :
foreach() :
if () :
.....
These variants allow yu to close the php tag after the ":" and whataver html / css / php / jquery you put in the condition / loop will be executed like normal...
For example you can do :
<ul>
<?php foreach ($row as $columnkey => $columnvalue): ?>
<img src="whateveryouwant"?>
<li class="<?php echo $columnkey;?>">This is my value: <?php echo $columnvalue; ?></li>
<?php endforeach; ?>
</ul>
When you do it this way it's much cleaner and you won't have any problems using double quatation signs and all that stuff :)
So using that method here is how your displayed list would look like in code:
<div class="entriesListMain">
<?php
$connection = mysql_connect("localhost", "username", "password"); // Establishing Connection with Server
$db = mysql_select_db("database_name", $connection); // Selecting Database
//MySQL Query to read data
$query = mysql_query("select * from results ORDER BY peemdate DESC", $connection);
while ($row = mysql_fetch_array($query)) :
?>
<div>
<input type="checkbox" name="<?php echo $row['family_id']; ?>" value="export">
<span><?php echo $row['client_id']; ?></span>
<span><?php echo $row['family_id']; ?></span>
<span><?php echo $row['firstname'] . " " . $row['lastname']; ?></span>
<span><?php echo date("d F Y",strtotime($row['peemdate']); ?></span>;
<span>
<a class="parents-button" href="peem-parent-repsonses.php?id=<?php echo $row['survey_id']; ?>">
<strong>Parent’s Review</strong>
</a>
</span>
<span>
<a href="peem-repsonses.php?id=<?php echo $row['survey_id']; ?>">
<strong>View Results</strong>
</a>
</span>
</div>
<?php endwhile; ?>
</div>
Like this the checkbox will get the name of the family ID, and so in your csv.php you can use this code :
while($row = mysql_fetch_row($result)) {
if ( array_key_exists($row['family_ID'], $_POST) {
fputcsv($fp, $row);
}
}
Since now it will check for each row wether the family ID of the SQL row is posted as a wanted row in the $_POST variable (checkbooxes) and if not it won't export the row into the csv file ! :)
So there you go ^^
EDIT 3: Troubleshooting
So there are a couple of things that you do in this function,
the form,
Do the checkboxes in your html form have the family_ID in their name attribute ?
(i.e. <input type="checkbox" name="<?php echo $row['family_id']; ?>".... check if the name attribute is really filled )
you post stuff from a form, (your checkboxes and stuff)so let's see what actually gets posted,
die(print_r($_POST)); - This means you want php to die after this line (stop working at all), then print out a variable as is (sort of xml format you'll see)
So then you will get a whole bunch of information, if you want to see this information in a nicely formated way, just right click inspect element on it :)
Then see how your checkboxes are coming out of the $_POST variable,
(they should have the family_ID as a key and a value of 1)
If that's all ok, then check your row['family_ID'] variable see if the family_ID is filled correctly, do the same with your whole $row variable, in fact check every variable you use in csv.php and then check why the key does not exist in the array you are searching for :)
Also dont forget to check that you filled the array_key_exists( has a key FIRST and an array[] LAST )
I can't help you directly with this , since this will propably be a faulty variable or a mistake in your form so try to find this yourself, if still nothing , post these variables values:
$_POST
$row
and the full HTML of your form
This is the code which selects from DB and sets the image tag.
<div>
<?php $query = mysql_query("SELECT * FROM company where sn='1'");
while($rows = mysql_fetch_assoc($query)){
$logo = $rows['logo'];
$password = $rows['password'];
$phone = $rows['phone'];
}
?>
<img src="<?php echo $logo ?>"/>
</div>
When we get this and set on textarea then we want this query{which save in db} executed. and output show only Logo name.
But this time this show full query which save in db.
we want get this output on textarea:
<div><img src="logoname"/></div>
You are using mysql extension, which is deprecated. You should use mysqli instead.
The loop overwrites your variables ($logo, $password, $phone) in every iteration, so it makes no sense until you're fetching single row.
But if you're fetching single row, then you don't need a loop:
<?php
if ($r = mysqli_query($connection, "SELECT * FROM company WHERE sn = 1")) {
$company = mysqli_num_rows($r) ? mysqli_fetch_row($result)[0] : null;
mysqli_free_result($r);
}
?>
<img src="<?php echo empty($company) ? 'nophoto.png' : $company['logo']; ?>" />
Replace
SELECT * FROM company where sn='1'
With
SELECT * FROM company WHERE sn=1
If you take out the apostrophes, that might solve your problem since the value stored in your database is most likely not a string. Also you should have WHERE in capital letters.
Let me know if that answered your question! :)
I want to make a link to delete a record from database using dynamic links with php however i couldn't figure it out
this is my code :
<?php
$query = "SELECT * FROM posts ";
$result = mysqli_query($connect, $query);
?>
<table>
<tr style="background: #afafaf;">
<th>Id</th>
<th>Title</th>
<th>Action</th>
</tr>
<?php
while($rows = mysqli_fetch_assoc($result)){
echo "<tr>";
echo "<td class=\"center\">".$rows['id']."</td>";
echo "<td>".$rows['title']."</td>";
echo "<td> delete</td>";
echo "</tr>";
}
?>
</table>
the output link would be like .../delete.php?id=X
can anyone help me write the code for delete.php ?
Have the below code in your page. This first checks if $_GET['id'] is set. It will only run if it is, that way you don't get Undefined Index error.
<?php
if (isset($_GET['id'])) {
$deleteId = htmlspecialchars($_GET['id'], ENT_QUOTES);
$delete = "DELETE FROM `posts` WHERE `id` = " . $deleteId;
}
?>
I also used htmlspecialchars to sanitize the user input. You could run some validation using ctype_digit to ensure that the input is actually an integer.
I suggest using prepared statement in MySQLi to prevent SQL injection.
Edit 1
Example with ctype_digit. This checks if the id is set and if it is a number, technically you could just use ctype_digit because if id is empty then ctype will return false as var_dump(ctype_digit("")); will return false, with that logic in mind, the value must be set for ctype_digit to work and it must be an integer.
<?php
if (ctype_digit($_GET['id'])) {
$deleteId = htmlspecialchars($_GET['id'], ENT_QUOTES);
$delete = "DELETE FROM `posts` WHERE `id` = " . $deleteId;
}
?>
That would be something like this:
$deleteId = $_GET['id'];
$sql = "DELETE FROM posts WHERE id = ".$deleteId;
Remember to escape your variables before sending them off to the MySQL server.
i have a problem:
if(isset($_POST['send'])){
$id = mysql_real_escape_string($_POST['id']);
$query = mysql_query("select * from somewhere where id='$id'");
$row = mysql_fetch_array( $query );
if(!mysql_num_rows($query)==1){
echo('error');
}
}
After this i have this echo from db:
<input type="text" name="up_name" value="<?php echo $row['name'];?>" id="up_name"/>
and this echo:
<select>
<?php
$up_id=$_POST['up_id'];
$sqlDateUser=mysql_query("SELECT `something` from `somewhere` where id='".$id."'");
$res=mysql_fetch_assoc($sqlDateUser);
$somethig_selected=$res['something'];
$something=mysql_query("SELECT `den` FROM `jud`");
while($row = mysql_fetch_row( $something)){
$selected=($row[0]==$somethig_selected)?'selected':'';
echo "<option value='".$row[0]."' ".$selected.">".$row[0]."</option>";
}
?>
</select>
In this order all it is ok but if i change it, first echo doesn't work. I need to display and others rows after these and i don't know what is the problem with the second echo. Can someone tell me what is the problem?
It may be a naming issue. For example, you have your second query assigning your values for mysql_fetch_row into a variable named $row.
That also is the same name you've given your first query, where you are assigning your mysql_fetch_array.
I would probably try naming them something different like $row_get_user_info and $row_get_den to differentiate them. Also it would make it easier if, when you moved your first echo line, that you also move the query that goes along with it. (Keep them together.)
In my Details table, when the complete field is '0' I want a certain image to appear when it is '1' I want a different image to appear. At the moment only the second image is showing (when complete field is 1)
This is the code I am using:
$id = $_SESSION['user_id'];
$isFinished= mysql_query("SELECT complete From details where user_id = $id") ?>
<p> <img src='<?php if($isFinished) echo "correct.png"; else echo "incorrect.png"; ?>' /><a href="details.php">Details</p>
Any ideas would be great!
The WHERE clause of your query is specifying only select records where complete = '1'
So you'll only get 1 back in the results.
You should remove that from the WHERE clause completely and let your php IF statement decide whether complete = '1'
the function
function getOne($query){
$res = mysql_query($query);
if (!$res) {
trigger_error("db: ".mysql_error()." in ".$query);
return FALSE;
}
if ($row = mysql_fetch_row($res)) {
return $row[0];
}
}
the code
$sql = "SELECT complete From details where user_id = ".intval($_SESSION['user_id']);
$isFinished = getOne($sql);
?>
<p>
<img src='<?php if($isFinished): ?>correct.png<? else: ?>incorrect.png<? endif ?>' />
Details
</p>
Your SQL statement only selects entries with complete='1'.
You should remove the "and complete='1'" from your statement.
Edite:
ALso as mentioned above your if statement only check if your query returned something or got an error.
It should be
if($isFinished['complete'] == '1') {echo "correct.png";}else{echo "correcy.png";}
It should be something like this:
$id = $_SESSION['user_id'];
$result= mysql_query("SELECT complete From details where user_id = $id and complete='1'") ?>
$row = mysql_fetch_array( $result );
<p>
<?php if($row['complete']): ?>
<img src="correct.png"/>
<?php else: ?>
<img src="incorrect.png"/>
<?php endif; ?>
<a href="details.php">
Details</a>
</p>
The mysql_query function returns false only when the query is invalid. It does not return false if there are zero rows.
You should use the mysql_num_rows function to determine if there was a row or alternatively use the mysql_fetch_* functions to fetch the value of complete.
Example 1 (Similar to your original (unedited) question):
$result = mysql_query("SELECT 1 From details where user_id = $id where complete = 1");
$isFinished = mysql_num_rows($result);
Example 2 (Alternative):
$result = mysql_query("SELECT complete From details where user_id = $id");
$record = mysql_fetch_assoc($result);
$isFinished = $record['complete'];
Is this the whole code?
In this case $isFinished is not the content retreived from db: mysql_query returns false if query is wrong otherwise an object where you can fetch the results.
In this case if($isFinished) is always true as the query is correct!
you miss the fetch part ater query execution!
http://php.net/manual/en/function.mysql-query.php
For example:
$id = $_SESSION['user_id'];
$result = mysql_query("SELECT complete From details where user_id = $id");
$isFinished= mysql_num_rows($result);
<p> <img src='<?php if($isFinished) echo "correct.png"; else echo "incorrect.png"; ?>' /><a href="details.php">Details</p>
This way if query returns one ore more rows then $isFinished is 1 or more otherwise $isFinished is 0. Your if - else should then work properly
Note i did not change the your original SQL, change it if you need.