Displaying data from databases - including images - php

This is my webpage:
http://www.autoweek62.uni.cc/carprice.php
Here is the source code for it:
<?php
$dbname = "autoweek_auto1";
$loginname = "autoweek_root";
$loginpass = "PASSWORD (not my real one)";
$dbhost = "localhost";
echo('<html><body bgcolor="#FFFFFF">');
echo('<font face="arial" size="+4"><center>');
echo("Database $dbname");
$id_link = #mysql_connect($dbhost, $loginname, $loginpass);
$tables = mysql_list_tables($dbname, $id_link);
$num_tables = mysql_num_rows($tables);
// store table names in an array
$arr_tablenames[] = '';
// store number of fields per table(index 0,1,2..) in an array
$arr_num_fields[] = '';
for ($i=0; $i < $num_tables; $i++) {
$arr_tablenames[$i] = mysql_tablename($tables, $i);
$arr_num_fields[$i] = mysql_num_fields(mysql_db_query($dbname, "select * from $arr_tablenames[$i]", $id_link));
}
// store field names in a multidimensional array:
// [i] == table number, [ii] == field number for that table
for ($i=0; $i < $num_tables; $i++) {
for ($ii=0; $ii < $arr_num_fields[$i]; $ii++) {
$result = mysql_db_query($dbname, "select * from $arr_tablenames[$i]", $id_link);
$hash_field_names[$i][$ii] = mysql_field_name($result, $ii);
}
}
for ($i=0; $i < $num_tables; $i++) {
echo("<center><h2>Table $arr_tablenames[$i] </h2></center>");
echo('<table align="center" border="1"><tr>');
$result = mysql_db_query($dbname, "select * from $arr_tablenames[$i]", $id_link);
for ($ii=0; $ii < $arr_num_fields[$i]; $ii++) {
echo("<th>");
echo $hash_field_names[$i][$ii];
echo("</th>");
}
echo("</tr><tr>");
$number_of_rows = #mysql_num_rows($result);
for ($iii = 0; $iii < $number_of_rows; $iii++) {
$record = #mysql_fetch_row($result);
for ($ii=0; $ii < $arr_num_fields[$i]; $ii++) {
echo("<td>");
echo $record[$ii];
echo("</td>");
}
echo("</tr>");
}
echo("</table>");
}
echo('</body></html>');
?>
It displays, but I'm not sure how to get it to display in a manner similar to this:
redbook.com.au/new-cars/results.aspx?Ns=p_Make_String|0||p_ClassificationType_String|0||p_Family_String|0||p_Year_String|1||p_SequenceNum_Int32|0&N=2994+2951+4294961316+4294843565&TabId=1407343
[not linked since I can't post more than 1 being new here]
(although mine is simply the make, model, bodystyle and prices as a list, not as complicated as the link above!)
I've Googled for some inspiration, but despite trying haven't got any far. I'm not looking for an instant answer, but any solutions are welcomed!
Displaying images is the trickiest part... I have the JPGs stored on the server, trying to get them to display is a problem.
All help is welcomed!

You could try making a separate script that returns just the image.
In that script you retrieve the image from the database, output mime-type header and then the raw image data. In your main HTML outputting script you just write <img src="getImage.php?id=1234" />

Related

PHP pagination. End array has different number of values than the initial query

Up until now I've always been limiting my pages for any pagination simply using MySQL LIMIT. It's been performing well.
However... Now I've written an application that grabs the data from 3 separate MySQL tables, after that I'm using array_multisort() to sort them.
The main issue here is that it is used for SMS messages(gammu smsd). If I write a message consisting of let's say 900 characters - it is split to 7 entries in the database. It is split every 139 characters (the number might be different sometimes)
Below code somewhat fixes this issue based on 'SequencePosition' field in the database.
So if I were to LIMIT it using MySQL I would have less results than I specified since MySQL has no idea what I'm doing with the data later.
I hope it makes sense to you guys.
How would you solve this issue? Can you think of a better way to do it? I mean- grabbing all the data from the table is rarely a good idea ;(
See PHP code below.
<?php
if(isset($_SESSION['id']))
{
if(isset($_GET['contact_number']) && ($_GET['contact_name']))
{
if (isset($_GET["page"]))
{
$page = $_GET["page"];
}
else
{
$page = 1 ;
}
$gmessages_page = 30; //this is actually a static value, normally it resides in a config file
$start_from = ($page-1) * $gmessages_page;
$contact_number = base64_decode($_GET['contact_number']);
$contact_name = base64_decode($_GET['contact_name']);
$query_inbox = "SELECT ReceivingDateTime, SenderNumber, TextDecoded FROM inbox WHERE SenderNumber='$contact_number' ORDER BY ReceivingDateTime";
$query_sentitems = "SELECT SendingDateTime, DestinationNumber, TextDecoded, Status, SequencePosition FROM sentitems WHERE DestinationNumber='$contact_number' ORDER BY SendingDateTime";
$query_outbox = "SELECT SendingDateTime, DestinationNumber, TextDecoded FROM outbox WHERE DestinationNumber='$contact_number' ORDER BY SendingDateTime";
$result_inbox = $conn->query($query_inbox);
$result_sentitems = $conn->query($query_sentitems);
$result_outbox = $conn->query($query_outbox);
if(!$result_inbox || !$result_sentitems || !$result_outbox)
{
die("Błąd połączenia z bazą (!RESULT)");
}
$rows_inbox = $result_inbox->num_rows;
$rows_sentitems = $result_sentitems->num_rows;
$rows_outbox = $result_outbox->num_rows;
if($rows_inbox == 0 || $rows_sentitems == 0)
{
$conn->close();
}
//inbox
$inbox_person = $contact_name;
for($j = 0; $j < $rows_inbox ; ++$j)
{
$result_inbox->data_seek($j);
$row_inbox = $result_inbox->fetch_array(MYSQLI_NUM);
$inbox_date[] = $row_inbox[0];
$inbox_number = $row_inbox[1];
$inbox_text[] = $row_inbox[2];
$sent_status[] = 0;
$sent_sequence_position[] = 0;
$inbox_type[] = 1;
}
for($j = 0; $j < $rows_sentitems ; ++$j)
{
$result_sentitems->data_seek($j);
$row_sentitems = $result_sentitems->fetch_array(MYSQLI_NUM);
if($row_sentitems[4] == 1)
{
$sent_sequence_position[] = $row_sentitems[4];
$inbox_date[] = $row_sentitems[0];
$inbox_text[] = $row_sentitems[2];
$sent_status[] = $row_sentitems[3];
$inbox_type[] = 2;
}
else
{
$inbox_text[sizeof($inbox_type) - 1] .= $row_sentitems[2];
}
}
for($j = 0; $j < $rows_outbox ; ++$j)
{
$result_outbox->data_seek($j);
$row_outbox = $result_outbox->fetch_array(MYSQLI_NUM);
$inbox_date[] = $row_outbox[0];
$inbox_text[] = $row_outbox[2];
$sent_status[] = "QueuedForSending";
$inbox_type[] = 2;
}
$number_of_records = sizeof($inbox_date);
$number_of_pages = ceil($number_of_records / $gmessages_page);
array_multisort($inbox_date, $inbox_text, $inbox_type, $sent_status, $sent_sequence_position);
$smarty->assign("inbox_date", $inbox_date);
$smarty->assign("inbox_text", $inbox_text);
$smarty->assign("inbox_number", $inbox_number);
$smarty->assign("inbox_person", $contact_name);
$smarty->assign("inbox_type", $inbox_type);
$smarty->assign("sent_status", $sent_status);
$smarty->assign("start_from", $start_from);
$smarty->assign("gmessages_page", $gmessages_page);
$smarty->assign("number_of_pages", $number_of_pages);
$smarty->assign("number_of_records", $number_of_records);
$smarty->assign("sent_sequence_position", $sent_sequence_position);
$smarty->assign("page", $page);
//for $_GET after sending SMS
$smarty->assign("contact_number_enc", $_GET['contact_number']);
$smarty->assign("contact_name_enc", $_GET['contact_name']);
$smarty->display('templates/conversation_body.tpl');
}
}
else
{
$smarty->display('templates/login_body.tpl');
}

Insert multiple users and random passwords Php&mysql

I am struggling to create multiple user&password and insert it in mysql column.
inserting multiple username is working but not multiple random password.
mysql table "users" - columns 'user' & 'password' primary key = user column
How it works:
A user enters a username and numbers (how many user & pass to create) in an HTML form.
The code uses the submitted username and adds a serial from "1" to limit (submitted number).
Example input:
submitted user is john
submitted numbers is 20
Example result:
john1, john2... john20
In the future when the user requests another 10 user & pass with same name "john" the number will start from 21 (john21, john22... john30)
adding another series is not done yet any help and tips are welcome.
My code:
function muser() {
function randomPassword() {
$alphabet = "abcdefghjkmnpqrstuwxyz23456789"; // skip 0OoIl1
$pass = array();
$alphaLength = strlen($alphabet) - 1;
for ($i = 0; $i < 6; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
return implode($pass);
}
if(isset($_REQUEST['submit'])) {
$user_input_user = $_REQUEST["user"];
$user_input_limit = $_REQUEST["limit"];
$ipass = randomPassword();
}
$uiuser = $user_input_user;
$uilimit = $user_input_limit;
$limit = $uilimit;
for($x = 1; $x <= $limit; $x++) {
$queryuser[] = "('$uiuser$x', '$ipass'),";
}
return implode($queryuser);
}
$mquery = 'INSERT INTO `users` (`user`, `pass`) VALUES ';
$imuser = muser();
$fquery = substr($imuser, 0, -1);
$sql = $mquery . $fquery .';';
The problem is caused because you give value to $ipass only once.
change the for loop from this
for($x = 1; $x <= $limit; $x++) {
$queryuser[] = "('$uiuser$x', '$ipass'),";
}
to
for($x = 1; $x <= $limit; $x++) {
$queryuser[] = "('$uiuser$x', '$ipass'),";
$ipass = randomPassword();
}

Distinguish between elements and last element of array

Im creating tablerows based on the number of the array colours:
$query = mysql_query("SELECT * FROM things);
$num = mysql_num_rows($query );
$colours = array ();
if($num)
{
for ($i = 0; ($row = mysql_fetch_assoc($query)); ++$i)
{
$colours[$i] = $row["colours"];
}
}
$arrlength = count($colours);
for ($i = 0; ($i < ($arrlength)); ++$i){
echo "
<tr class='border_bottom'><td>".$colours[$i]."</td></tr>
";
}
So, if colours is, lets say, equal to 8, 8 table rows with the class border_bottom are created.
border_bottom is used by CSS to add a border to the bottom of each tablerow.
What I need is some PHP help: I need code which checks the array colours. The last element of the array has to go with an empty id since I dont want a border-bottom added to that very last tablerow. All other tablerows have to go with the border_bottom class, tho.
I was thinking of starting the code like that:
echo"
<tr class='
";
-->PHP code goes here<--
echo"
'>
<td>".$colours[$i]."</td></tr>
Try this:
<?php
$query = mysql_query("SELECT * FROM things");
$num = mysql_num_rows($query);
$colours = array();
if($num)
{
while($row = mysql_fetch_assoc($query))
{
$colours[] = $row["colours"];
}
}
$arrlength = count($colours);
for ($i = 0; $i < $arrlength; ++$i){
if($i < $arrlength - 1){
echo "<tr class='border_bottom'><td>{$colours[$i]}</td></tr>";
}else{
echo "<tr><td>{$someColor}</td></tr>";
}
}
Try the following code in your table row echo
echo "<tr"
.($i < $arrlength - 1 ? " class='border_bottom'" : "")
.">"
."<td>{$colours[$i]}</td></tr>";
You can actually do this while fetching the rows without needing to count how many there are, by reading ahead one row.
$previous_row = mysql_fetch_array(); // fetch the first row (if there is one)
while ($previous_row) {
if ($row = mysql_fetch_array()) {
// if another row is fetched, then the previous row was NOT the last row
echo '<tr class="border_bottom"><td>' . $previous_row['colours'] . '</td></tr>';
} else {
// otherwise, the previous row WAS the last row, and does not get the class
echo '<tr><td>' . $previous_row['colours'] . '</td></tr>';
}
$previous_row = $row; // Set the previous row to the current row
}

Export MySQL database to CSV while converting Unix to date

A little bit of backstory first. I have a database that works with a custom created ticket system. New tickets are input via a HTML form that uses PHP.
I need to be able to export certain results to a CSV depending on what the users selects on a separate form.
A quick google of MySQL to CSV with PHP brings this website up.
http://www.a2zwebhelp.com/export-data-to-csv.
I've amended the code slightly so that the query doesn't select all columns from my table, below is my amended code.
<?php
// Database Connection
$host="localhost";
$uname="REMOVED";
$pass="REMOVED";
$database = "REMOVED";
$connection=mysql_connect($host,$uname,$pass);
echo mysql_error();
//or die("Database Connection Failed");
$selectdb=mysql_select_db($database) or die("Database could not be selected");
$result=mysql_select_db($database)
or die("database cannot be selected <br>");
// Fetch Record from Database
$output = "";
$table = "site_calls"; // Enter Your Table Name
$sql = mysql_query("select call_id, call_first_name, call_email, call_department, call_subject, call_status, call_user, call_date, call_date2 from $table WHERE (call_user = 15)");
$columns_total = mysql_num_fields($sql);
// Get The Field Name
$columns = ["call_id","call_first_name","call_email","call_department","call_subject","call_status","call_user","call_date","call_date2"];
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
$output .= '"'.$heading.'",';
}
$output .="\n";
// Get Records from the table
while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}
// Download the file
$filename = "TicketExport.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $output;
exit;
?>
This almost does exactly what I want it to do. The only problem, is due to the way time/date is saved in the database (Unix) the output of 2 columns call_date and call_date2 are output as Unix. I need these to come out as DD/MM/YY or another human readable format. I can manually change this using a formula in excel, but this is something that a customer would have access to, and they'll need to be able to read the date.
Also, mysql is depreciated, are there significant changes to the above code to get it working on mysqli. The rest of the system is written using mysqli for inputting the data.
TL:DR. Exporting some columns from a MYSQL database, need to convert 2 columns from Unix to readable date/time using php.
Try this :
while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
if ($heading == 'call_date' || $heading == 'call_date2') {
$output .= '"'.date('d/m/y', strtotime($row["$i"])).'",';
}
else {
$output .='"'.$row["$i"].'",';
}
}
$output .="\n";
}
Use an if statement inside the for loop to identify you are on the date columns, then call the php date function to reformat.
Like this:
for ($i = 0; $i < $columns_total; $i++) {
if($i == 7 or $i == 8) {
$output .='"'.date('d/m/y', strtotime($row["$i"])).'",';
} else {
$output .='"'.$row["$i"].'",';
}
}
I hope this helps!

variable increment doesn't work

When I launch my web page, increment doesn't work correctly!
It should go like this: $i = from 1 to x (0,1,2,3,4,5,6 etc..).
But instead it jumps over every step giving result of (1,3,5,7 etc..).
Why is this code doing this?
<ul class="about">
<?php
$result = mysql_query("SELECT * FROM info WHERE id = 1");
while ($row = mysql_fetch_assoc($result))
{
$bioText = $row['bio'];
}
$endBioTxt = explode("\n", $bioText);
for ($i=0; $i < count($endBioTxt);)
{
if (checkNum($i) == true)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
$i++;
}
// Function to check if number is prime
function checkNum($num){
return ($num % 2) ? TRUE : FALSE;
}
?>
</ul>
Output:
Sometext!(right side)
0
1
Sometext2!(right side)
2
3
...
Please DONT do this as other suggested:
for ($i=0; $i < count($endBioTxt); $i++)
do this:
$count = count($endBioTxt);
for ($i=0; $i < $count; $i++) {
}
No need to calculate the count every iteration.
Nacereddine was correct though about the fact that you don't need to do:
$i++;
inside your loop since the preferred (correct?) syntax is doing it in your loop call.
EDIT
You code just looks 'strange' to me.
Why are you doing:
while ($row = mysql_fetch_assoc($result))
{
$bioText = $row['bio'];
}
???
That would just set $bioText with the last record (bio value) in the recordset.
EDIT 2
Also I don't think you really need a function to calculate the modulo of a number.
EDIT 3
If I understand your answer correctly you want 0 to be in the left li and 1 in the right li 2 in the left again and so on.
This should do it:
$endBioTxt = explode("\n", $bioText);
$i = 0;
foreach ($endBioTxt as $txt)
{
$class = 'left';
if ($i%2 == 1) {
$class = 'right';
}
echo '<li class="'.$class.'"><div>'.$txt.'</div></li>';
echo $i; // no idea why you want to do this since it would be invalid html
$i++;
}
Your for statement should be:
for ($i=0; $i < count($endBioTxt); $i++)
see http://us.php.net/manual/en/control-structures.for.php
$i++; You don't need this line inside a for loop, it's withing the for loop declaration that you should put it.
for ($i=0; $i < count($endBioTxt);$i++)
{
if (checkNum($i) == true)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
//$i++; You don't need this line inside a for loop otherwise $i will be incremented twice
}
Edit: Unrelated but this isn't how you check whether a number is prime or not
// Function to check if number is prime
function checkNum($num){
return ($num % 2) ? TRUE : FALSE;
}
This code works, please test it in your environment and then uncomment/comment what you need.
<?php
// This is how query should look like, not big fan of PHP but as far as I remember...
/*
$result = mysql_query("SELECT * FROM info WHERE id = 1");
$row = mysql_fetch_assoc($result);
$bioText = $row['bio'];
$endBioTxt = explode("\n", $bioText);
*/
$endBioTxt[0] = "one";
$endBioTxt[1] = "two";
$endBioTxt[2] = "three";
$endBioTxt[3] = "four";
$endBioTxt[4] = "five";
$totalElements = count($endBioTxt);
for ($i = 0; $i < $totalElements; $i++)
{
if ($i % 2)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
}
/*
// This is how you should test if all your array elements are set
if (isset($endBioTxt[$i]) == false)
{
echo "Array has some values that are not set...";
}
*/
}
Edit 1
Try using $endBioTxt = preg_split('/$\R?^/m', $bioTxt); instead of explode.

Categories