Quantcast
Channel: PHP Freaks: PHP Help
Viewing all 13200 articles
Browse latest View live

Looping webimages

$
0
0

I have a website of grids of webcam images.

I have decided to make a looping webpage where I want just 1 image per page and every 2 seconds moves on to the next image.

 

I have the following code - but it only gets 1 image.  I was going to update the database record  with the next image but have decided it will be easier to get an array and loop round that somehow.  Normally when I loop its easy to display the results in a table but this time i want it to display 1 image (record) at a time then move on...

 

The code below works fine (only showing the first image form the website in my database)

 

I hope someone can help me out please.

TIA

<html>
<head>
<title>My webcam page </title>
</head>


<?php


    $host = 'localhost';    
    $user = 'my_User';
    $pass = 'my_Password';
    $db = 'my_db';


    $con = mysqli_connect($host, $user, $pass, $db) or die(mysqli_connect_error());


    $sql = "SELECT * FROM `websites` WHERE `currentshowing`=1 LIMIT 0, 30 ";
    $result  = mysqli_query($con,$sql);
    if (!$result) 
    {
        die("Error: Data not found..");
    }
    $test = mysqli_fetch_array($result);
    $webpic=$test['webpic'];
    $basesite=$test['basesite'];
    $location=$test['location'];
    
?>


<div align="center">
<h1>MY WEBSITE (Ongoing work)</h1>
</div>


<td><div align="center"><?PHP echo $location; ?><br>
        <a href="<?PHP echo $basesite; ?>">
        <img src="<?PHP echo $webpic; ?>" 
        alt="<?PHP echo $location; ?>" 
        width="80%" border="0"/>
        </a></div></td>


</body>
</html>
 

Help with MySQLi

$
0
0

I have just started using MySQLi and am clueless it is giving me the follow errors in which i do not understand

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\xampp\htdocs\Login\connect.php on line 23

Notice: Trying to get property of non-object in C:\xampp\htdocs\Login\connect.php on line 25

Notice: Use of undefined constant mysqli - assumed 'mysqli' in C:\xampp\htdocs\Login\connect.php on line 32

Warning: mysqli_query() expects parameter 1 to be mysqli, string given in C:\xampp\htdocs\Login\connect.php on line 32

Warning: mysql_fetch_assoc() expects parameter 1 to be resource, null given in C:\xampp\htdocs\Login\connect.php on line 33
 

 

can someone please explain to me why i am getting these?

 

and my code is

$mysqli_db = mysqli_select_db("$db_name");

if($mysqli_db->connect_errno) {

	printf("Database not found: %s\n", $mysql->connect_error);
	exit();
}

$sql = "SELECT * FROM $tbl_name WHERE username='$username' AND password='$password'";
$result = mysqli_query($sql);
$row = mysqli_fetch_assoc($result);

I just got rid off most the errors the only ones left are 

Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\xampp\htdocs\Login\connect.php on line 32

Fatal error: Call to undefined function mysqli_result() in C:\xampp\htdocs\Login\connect.php on line 33

 

Code Updated: 

$mysqli_db = mysqli_select_db($mysqli_connect, $db_name);

if(!$mysqli_db) {

	printf("Database not found: %s\n", $mysqli->connect_error);
	exit();
}

$sql = "SELECT * FROM $tbl_name WHERE username='$username' AND password='$password'";
$query = mysqli_query($sql);
$result = mysqli_result($query);
$row = mysqli_fetch_assoc($result);

confused

$
0
0

everytime i run my code i get ( ! ) Warning: mysqli_query() expects parameter 2 to be string, object given in C:\wamp\www\Tutorial\test.php on line 5. i just cant seem to find the error

my code looks like this 

 

Attached Files

  • Attached File  test.php   312bytes   8 downloads

Php Script that generate another

$
0
0
I'm trying to use a php script to generate another php script copying from a "stub" that has replacement tags. The problem I'm facing is opening a "stub" php script and reading it line by line. I've tried multiple functions: file_get_contents(), print_r(file($file)), where $file = fopen(filename). fgets, etc. echo file_get_contents() spits out the file only starting at a certain point, so I have wondered if it is trying to run the php that is in there. The odd thing, is that if I create a new file with exactly the same content, it won't display anything! 
    Currently I have:
Code: 
<?php
    if( file_exists("Stubs/test.txt")){
    echo "This works!";
    echo file_get_contents('Stubs/test.txt');
}
else{
    echo "This doesn't work!";
}
?>
 
and the txt file:
Code: 
<?php
 
require_once('util/import/ListHubImport.php');
 
class CBGoldKeyRealtyIncUTImport extends ListHubImport
{
 
    public function __construct($date = null, $printMessages = true)
    {
        parent::__construct(CO_ImportScript::CBGOLDKEYREALTYINCUT, $printMessages, null, 'Coldwell Banker Gold Key Reality Inc.');
 
        // CONNECTION INFO
        $dataConn = new DataConnection();
        $dataConn->setConnectionType(DataConnection::HTTP);
        $dataConn->setValidOfficeIds(array('38575'));
 
        $this->connectionInfo = $dataConn;
 
        $this->setSaveFilename($dataConn->getSaveDataPath() . "CBGoldKeyRealtyInc-UT_::DATE::.xml");
 
        $this->date = $date;
        $this->setSaveRecords(true);
        $this->fields = $this->skippedListings = array();
//...
 
    }
 
}
 
?>
 
This behavior is bizarre to me, and I'm running out of debugging options with php. Any help would be appreciated! Thanks. -Luc
 
PS. It shows everything from the line: $dataConn = new DataConnection(); to the end of the file.

Connecting to Database and Displaying the Row

$
0
0

So I've followed this code, corrected about 12 error, talked to my hosting and I am so done. I have tried everything but the error won't go away. The code is pasted below. As it's really late any help would be appreciated that would make my day the next day...  ;D

 

<?PHP
//connect to server
$connect = mysql_connect("localhost","cello10_import","brigite27");
//connection to database
mysql_select_db("cello10_import");
//query the database
$query = mysql_query("SELECT * FROM users WHERE cover_image = 'http://d1w7fb2mkkr3kw.cloudfront.net/assets/images/book/small/9781/2500/9781250038821.jpg' ");
//fetch the results / convert into array
 
WHILE($rows = mysql_fetch_array(query)):
 
$cover_image = $rows['cover_image'];
$title = $rows['title'];
$author = $rows['author'];
 
echo "$cover_image<br>$title<br>$author<br><br><br>";
 
endwhile;
?>
 
The error experienced is: 

Warning: mysql_fetch_array() expects parameter 1 to be resource, string given in /home/cello10/public_html/display.php on line 10

 

Thanks for your help  :sweat: 

PHP generated website skeleton

$
0
0

This is a slimmed down bit of PHP code that I use to make the sites that I make.
<?
include("menu.txt");
if (!isset($_GET['page'])) {
    include("mainpage.txt");
    exit;
}
if (file_exists($_GET['page'] . ".txt")) {
    echo "<script type='text/javascript'>document.title='Website - " . ucfirst($_GET['page']) . "';</script>";
    include($_GET['page'] . ".txt");
    exit;
  } else {
    include("404errorpage.txt");
    exit;
   }
}
?>
The nav links to other pages would be similar to this code
The text files that get included to make up the different pages of the site can be in the main docroot directory, in a subdirectory, or be in another 'parent' directory. These text files can be made up of any combination of J/S, PHP, HTML, or just plain old text. CSS can be used to make all this look nice.
 

Display data in tabular format by year and month

$
0
0

Hi,

 

I want to display my data in this format

format.JPG

 

Expense data i am getting like this

 <td><?php
	$in = "SELECT sales_invoice.invoice_id as INID, DATE_FORMAT(sales_invoice.date_invoiced,'%M') AS month, sales_invoice_line_items.invoice_id, SUM(sales_invoice_line_items.sub_total) AS Total, SUM(sales_invoice_line_items.tax_amount) AS total_tax FROM sales_invoice INNER JOIN sales_invoice_line_items ON sales_invoice.invoice_id=sales_invoice_line_items.invoice_id GROUP BY sales_invoice.invoice_id, DATE_FORMAT(sales_invoice.date_invoiced, '%Y-%m')";
	
	$in1 = mysql_query($in) or die (mysql_error());
	$total=0;
	$tax =0;
	while($income = mysql_fetch_array($in1))
	{
		
		$total +=$income['Total']; 
		$tax +=$income['total_tax'];
		echo $total - $tax; }
    ?>
    
    </td>

And Profit i am getting like this

<td><?php
	$in = "SELECT purchase_invoice.invoice_id as INID, DATE_FORMAT(purchase_invoice.date_invoiced,'%M') AS month, purchase_invoice_line_items.invoice_id, SUM(purchase_invoice_line_items.sub_total) AS Total, SUM(purchase_invoice_line_items.tax_amount) AS total_tax FROM purchase_invoice INNER JOIN purchase_invoice_line_items ON purchase_invoice.invoice_id=purchase_invoice_line_items.invoice_id GROUP BY purchase_invoice.invoice_id, DATE_FORMAT(purchase_invoice.date_invoiced, '%Y-%m')";
	
	$in1 = mysql_query($in) or die (mysql_error());
	$total=0;
	$tax =0;
	while($income = mysql_fetch_array($in1))
	{
		
		$total +=$income['Total']; 
		$tax +=$income['total_tax'];
		echo $total - $tax; }
    ?>
    
    </td>

I dont know how to display data like this. Do i need to change the the table structure in my database? Please suggest

How to run 2 queries based on input value

$
0
0

Hi

 

I have a form that has a drop-down with a few to choose from, unfortunately I don't get results for some due to the query involved.

Some need the AND channel LIKE '%$channel%'"; and some don't and therefore will not get desired results. So I would like to run two queries one with and one without.

 

$query = "SELECT * FROM asterisk_cdr WHERE calldate BETWEEN '$calldate' AND '$calldate2' AND clid LIKE '%$clid%' AND channel LIKE '%$channel%'";

 

Thanks

 


Specific file types upload not working

$
0
0

I am in the process of creating a script where only certains video types can be uploaded but at the moment am stuck.

Here is my code -

<?php

$title = isset($_POST['title']) ? $_POST['title'] : null;
$desc = nl2br(isset($_POST['description'])) ? $_POST['description'] : null;
$name = isset($_POST['fullname']) ? $_POST['fullname'] : null;
$email = isset($_POST['email']) ? $_POST['email'] : null;
$country = isset($_POST['country']) ? $_POST['country'] : null;

$video = isset($_FILES['video']);
$videoname = isset($_FILES['video']['name']);
$videotmp = isset($_FILES['video']['tmp_name']);
$videosize = isset($_FILES['video']['size']);
$videotype = isset($_FILES['video']['type']);
$videoacceptable = array(
        "video/mp4",
        "video/ogg",
        "video/quicktime",
);

$videopath = "/videos/";
$videofile = $videopath . $video;

if(isset($_POST['submit'])) {

//ERROR MESSAGES / VALIDATION

if(empty($title)) {
    $errors[] = "A title is required"; 
    echo "<style type=\"text/css\"> #title { background-color:#F5A9A9;border:1px solid #DF0101; } </style>";
} elseif(strlen($title) > 80) {
    $errors[] = "Your title can only be 80 characters long"; 
    echo "<style type=\"text/css\"> #title { background-color:#F5A9A9;border:1px solid #DF0101; } </style>";
}
if(empty($desc)) {
    $errors[] = "A description is required";
    echo "<style type=\"text/css\"> #description { background-color:#F5A9A9;border:1px solid #DF0101; } </style>";
}
if(empty($name)) {
    $errors[] = "Please enter your full name";
    echo "<style type=\"text/css\"> #fullname { background-color:#F5A9A9;border:1px solid #DF0101; } </style>";
} elseif(strlen($name) > 32) {
    $errors[] = "Your name can only be 32 characters long";
    echo "<style type=\"text/css\"> #fullname { background-color:#F5A9A9;border:1px solid #DF0101; } </style>";
}
if(empty($email)) {
    $errors[] = "Please enter your email address";
    echo "<style type=\"text/css\"> #email { background-color:#F5A9A9;border:1px solid #DF0101; } </style>";
} elseif(strlen($email) > 50) {
    $errors[] = "Your email addess can only be 50 characters long";
    echo "<style type=\"text/css\"> #email { background-color:#F5A9A9;border:1px solid #DF0101; } </style>";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors[] = "Please enter a valid email address";
    echo "<style type=\"text/css\"> #email { background-color:#F5A9A9;border:1px solid #DF0101; } </style>";
}
if($videosize = 0) {
    $errors[] = "You forgot to upload a video";
} elseif($videosize >= 20000000) {
    $errors[] = "Your video size is too large, 20mb max";
} elseif(!in_array($videotype, $videoacceptable)) {
    $errors[] = "The file type is not allowed, only allowed .mp4, .ogg and .mov";
}

if(count($errors) === 0) {
    $connect = mysqli_connect("localhost","username","password");
        if(!$connect) {
            header("Location:"); // ADD ERROR LINK
        }
    $dbselect = mysqli_select_db("database");
        if(!$dbselect) {
            header("Location:"); // ADD ERROR LINK
        }

    $query = mysqli_query("INSERT INTO cover_videos(title, desc, name, email, country, videotmp, videotype, videosize, videopath) VALUES('$title','$desc','$name','$email','$country','$videotmp','$videotype','$videosize','$videopath')");
    move_uploaded_file($videotmp, $videofile);

    //SEND AN EMAIL TO THE USER     
    $to = $email;
    $subject = "Thank's for your upload";

    $message = '
        <html>
            <head><title>We have received your video</title></head>
            <body>
                <h3>Good News!</h3>
                <p>We have recieved your video and is awaiting approval.</p>
            </body>
        </html>
    ';

    $headers = 'FROM: no-replyk' . "\r\n";
    $headers = 'MIME-Version: 1.0' . "\r\n";
    $headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    $headers = 'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);

    header("Location:"); //SUCCESSFUL UPLOAD PAGE

    }

}

?>

So whats happening is when i go to upload a file, im uploading a .mov file but the error message that pops up is "The file type is not allowed, only allowed .mp4, .ogg and .mov" but the .mov mime is in the videoacceptable array so im a bit stuck at the moment, any know whats the problem?

allowing user choose from multiple rows

$
0
0

I know the title is a bit confusing but I wasn't exactly sure how to describe my issue and none of my numerous searches online and here returned any positive results for a solution.

What I'm trying to do is allow a user to 'choose' one set from multiple sets of numbers for inclusion into the database. The image below should with the visualization of my goal.

sets.png

 

As you can see from the above image, there's a "button" to the right that states "keep this set". My goal is to allow the user to click the button and the corresponding set of values is then entered into the database as a string (the values aren't being used in any calculations afterwards just being displayed on screen.)

The following code below works for auto-insertion if there's only one set generated but nothing I've attempted so far works when it comes to allowing the user to choose one set they'd like entered.

    <?php

additional code here...

    echo '<table><tr><td>';

    for($i=1; $i<=$Sets; $i++){
        $Stat_Results = GenStats($uId, $StartSet, $SetOption);

        echo "Stat values for ".$SetGenerated[$i];

       foreach($Stat_Results as $key => $DisplayStats){
              echo $DisplayStats.', ';
       }

       if($Sets == 1){
         $SetResults = implode(',',$Stat_Results);
         DB_Insert($uId, $SetResults, $TimeStamp);    
       }else if($Sets >= 2){
         echo "</td><td> => <input type='button' name='submit' value='keep this set'></td>
         <tr><td>";
       }
    }    
    echo '</td></tr></table>';
    ?>

html below here....

Variables: $sId, $StartSet, $SetOption, $Sets, $uId, and $TimeStamp are all set in a section not shown in this snippet.

I've tried Javascript but too be honest, I'm not all that familiar with it (though I am trying to become more fluid in it) and I've went so far as to try to create the multiple sets as a dropdown box thinking the user could simply select it from there and it be treated as a dynamic form and php would do the rest. But that didn't work either. The form button for submission is the remnant of the <select> list I tried to generate. The form is no longer there. I left the button in to generate the image you see above and has since been removed from the actual code.

I admit, I'm stuck and need some guidance because I can't seem to make this work no matter what I do. I realize $Stat_Results is a multidimensional array and contains all the values of each set in their respective array, but so far, I'm at a stand still on properly retrieving those values for insertion.

Thanks to all who read and attempt to help!

Setting Session Variables

$
0
0

I have created a test account in my database with a user level of -1 and i think my code might be wrong but i am hoping someone can spot where i have gone wrong as i cannot, also a similar problem with another session variable loggedIn this is what i get when i login this is on the index page.

Notice: Undefined index: loggedIn in C:\xampp\htdocs\Login\index.php on line 11

Notice: Undefined index: loggedIn in C:\xampp\htdocs\Login\index.php on line 17
You must be logged in to view this page!

Index page source code: 

<?php

session_start();

error_reporting(E_ALL | E_NOTICE);

ini_set('display_errors', '1');

require 'connect.php';

if($_SESSION['loggedIn'] == 1) {

	//Do Nothing

	exit();
	
} else if($_SESSION['loggedIn'] != 1) {

	echo "You must be logged in to view this page!";

	exit();
}

if($_SESSION['user_level'] == -1) {

	header("Location: banned.php");

} if(isset($_SESSION['username'])) {

	echo "<div id='welcome'> Welcome, ". $_SESSION['username'] ." <br> </div> ";

}

?>

Also if you need my login source code: 

<?php
error_reporting(E_ALL | E_NOTICE);

require 'connect.php';

session_start();

if (isset($_POST['submit'])) {
   
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
   
    if (empty($username)) {
       
        echo "You did not enter a username, Redirecting...";
       
        echo "<meta http-equiv='refresh' content='2' URL='login.php'>";
       
        exit();
       
    }
   
    if (empty($password)) {
       
        echo "You did not enter a password, Redirecting...";
       
        echo "<meta http-equiv='refresh' content='2' URL='login.php'>";
       
        exit();
       
    } 
   
    //Prevent hackers from using SQL Injection to hack into Database
    $username = mysqli_real_escape_string($con, $_POST['username']);
    $password = mysqli_real_escape_string($con, $_POST['password']);

	$result = $con->query("SELECT * FROM $tbl_name WHERE username='$username' AND password='$password'");

	$row = $result->fetch_array();

	$user_level = $row['user_level'];


// check to make sure query did execute. If it did not then trigger error use mysqli::error to see why it failed
if($result->num_rows > 0)
{

//Set default user
	$_SESSION['loggedIn'] == 1;
	$_SESSION['user_level'] == 1;
	$_SESSION['username'] == trim($_POST['username']);
	header("Location: index.php");
	exit();	
} else if($row['user_level'] == 1) {

		$_SESSION['user_level'] == 1;

		//Location admin 
		header("Location: admin.php");

		exit();

	} else if($row['user_level'] == -1) {

		$_SESSION['user_level'] == -1;

		$_SESSION['username'] == trim($_POST['username']);

		//Location banned
		header("Location: banned.php");

		exit();
	} else if($_SESSION['loggedIn'] == true) {

		//Location default user home page
		header("index.php");
	} else {

		echo "Invalid Username/Password";
	}


  //Kill unwanted session
} if(isset($_POST['killsession'])) {

	session_destroy();
	echo "<br> <br> The Session Destroyed. (Basically means you have been logged out)";
	exit();

	}

?>

I appreciate all help :)

Maze Map with PHP / Serverside storage

$
0
0

Just curious, how would you go about rendering and storing this in a database. For example a simple small maze. 

 

4b1b079f8c72a397f2f159d1e24636ee.png

 

With each keypress, the user is moved up,down,left,right like 1 inch. (1 block). Which is easy to do with jquery, etc. But how would go about storing the data in a databse (can update the position per update or using websockets), but essentially so maphacks are impossible and everything is saved/read from the server.

 

Would the storage data be something like [0,0,0,1,0,0,1,1,1,1,0,1] I imagine or what?

IF % is greater than 50% get fields from txt and DB then send email

$
0
0

I would like to send an email when % is >than 50%, if so get fields from Txt fiel and fields from DB and send an email to the address in the txt file. 

 <html>
<head><title>Email Alert</title></head>
<body>
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;

//$mail->SMTPDebug = 3;                               // Enable verbose debug output
mysql_connect("ip","user","pass") or die(mysql_error());
//mysql_select_db("DB") or die(mysql_error());
//$sql = "SELECT * from pool";



$sql = mysql_db_query ("demo", "select * from pool ");
while ($row = mysql_fetch_assoc($sql)) {
$sql = "SELECT '%' FROM pool Where >= 50 ";
{   
    //echo $row->number;

    $percent = $row['%'] ;
    $pool2 = $row['pool'];
    $balance = $row['balance'];
   


///////////////////////////
//data from file //////////
//////////////////////////   

$file = fopen('EmailAndPool2.csv', 'r');
$fields = array();

if ($file) {
    while (($data = fgetcsv($file)) !== false) {
     

        if(empty($fields)) {
            $fields = $data;
            continue;
        }

      
        $row = array_combine($fields, $data);

        // Format output conveniently with sprintf
        $output = sprintf("%s Pool %s email.\n",
                          $row['pool'],
                          $row['email']);
        echo $output;
    }
    fclose($file);

$pool1 = $row['pool'];

//while ($pool2 == $pool1 and $percent > "50")

$pool2 =$row['pool2'];
$mail = new PHPMailer;
$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'xxxxxxxxx;  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'xxxxxxxxxxxxxxxxx';                 // SMTP username
$mail->Password = 'xxxxxxxxxxxxxxxx;                           // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587;                                    // TCP port to connect to

$mail->FromName = 'Support';
$mail->addAddress ($row['email']);
//$mail->addAddress = $members;
//$mail->addCC('xxxxxxxxxxx'); 
//$mail->addCC('xxxxxxxxxxxxxxxx'); 
$mail->WordWrap = 50;                                 // Set word wrap to 50 characters

$mail->isHTML(true);     
$mail->Subject = 'test';
$mail->Body    = 'test ';
$email_from = 'xxxxxxxxxxxx';


}
if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}
}
}

?>

    </body>
</html>

Thank you 

SQL Display using WHERE

$
0
0

So I have this script. I connected the database and verified a working connection to the base, password correct. As I save the script on my server it saved the changes and I view the file online. The resulting page is blank. Really need help completing this code as it's essential to my sites organization, have a look below and help me if possible.

 

<?php
 
//make connection
mysql_connect('localhost', 'cello10_employees', 'brigite27');
 
//select db
mysql_select_db('cello10_tutorials');
 
$sql="SELECT * FROM employees
WHERE age='23'";
?>
 
Thanks
Emanuel

update php mysql using fancybox not working please help

$
0
0

view_leader.php

 
<?php
include('../connect.php');
$message = "";
$id =$_REQUEST['id'];
$rs = mysql_query("SELECT * FROM leaders WHERE id  = '$id'");
$test = mysql_fetch_array($rs);
if (!$rs) 
{
die("Error: Data not found..");
}
$fname=$test['lname'] ;
if(isset($_POST['save']) )
{
$lname_save = $_POST['fname'];
 
mysql_query("UPDATE leaders SET lname ='$lname_save' WHERE id = '$id'")
or die(mysql_error()); 
echo "Saved!";
header("Location:../leaders.php");
}
mysql_close();
?>
<!DOCTYPE html>
<html>
<head>
<title>Restricted</title>
</head>
 
<body>
<form method="post">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="fname" value="<?php echo $fname ?>"/></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="save" value="Save" /></td>
</tr>
</table>
</body>
</html>
 
and this is the edit link
 
 
<a id='edit' class='iframe various' title='Update $names ?' href ='trans/view_leader.php?id=$id'><i class='fa fa-edit'></i></a>
 

Combine an HTML form with a display of search results over several pages

$
0
0

  In the code below, I am trying to produce a google-like page where the user can type keywords
and pages of search results are displayed.
  The main difficulty I am encountering is that when the browser changes pages, it forgets everything about current data.    Perhaps I should include the display of pages inside the HTML form ? How can I fix this code ?
 

 Here is the contents of my searchpage.php file :

<?php



$keywords='';
$display_search_results='';

if(isset($_POST['search_submitted'])) {
    $keywords=$_POST['keywords'];
    $search_results=array();
    $totalNbrOfItems=20;
    for($k=1;$k<=$totalNbrOfItems;$k++) {
      $search_results[$k]='Your keywords '$keyowrds.' have been found in item number '.$k;
    }  

    $nbrOfItemsParPage = 5;
    $nbrOfPages = ceil($totalNbrOfItems / $nbrOfItemsParPage);
    // Compute current page
    $current_page = (isset($_GET['page']))?intval($_GET['page']):1;
    $display_pages=($nbrOfPages<2)?'<p>Page : ':'<p>Pages : ';
    for ($i = 1 ; $i <= $nbrOfPages ; $i++)
    {
        if ($i == $current_page) //No link to the current page
        {
            $display_pages=$display_pages.$i.' ';
        }
        else
        {
            $display_pages=$display_pages.'<a href="searchpage.php?'.
            'page='.$i.'">'.
            $i . '</a> ';
        }
    }
    $display_pages=$display_pages.'</p>';
    $display_items='';
    $start=$nbrOfItemsPerPage*($current_page-1);
    for($k=1;$k<=$nbrOfItemsParPage;$k++) {
      $display_items=$display_items.($search_results[$start+$k]).'<br>';
    }
    $display_search_results=$display_pages.$display_items;
}


echo '<form method="post" action="searchpage.php">'.
' Type your keywords here : <br><br>'.
'<textarea cols="65" rows="1" '.
'id="keywords_id" name="keywords">'.$keywords.'</textarea>'.
'<input type="submit" name="search_submitted" id="search_submitted_id" value="Search" /> '.
'</fieldset>'.
'</form>';

echo $display_search_results;

?>

help simple PHP code

$
0
0

Hi! 

I'm new to php so, please forgive if this is a really simple question or if it doesn't make sense.

 

I have an www.domain.com web site and then I have an microprocessor at home connected to the internet also hosting and simple page. That page is acessible from the internet.

 

When I'm browising on my www.domain.com i want to add an botton that sends an request to the microprocessor, right now what i do is when the button is clicked, it opens the microprocessor page like : microprocessor.ddns.net/?update=1. 

 

How can i make the www.domain.com send the "?update=1" to the microprocessor without the user have to see the microprocessor page. 

The main purpose is to hide the microprocessor address so it's harder to be hacked.. 

 

Thanks for the help! 

XML parsing

$
0
0

I can't seem to get this to parse into an array:

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<ns:getReportTestResponse xmlns:ns="http://webservice.avm.pvads.com">
<ns:return xmlns:ax21="http://webservice.avm.pvads.com/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ax21:WSReportBean">
<ax21:confidence />
<ax21:dateStamp>12/07/2007</ax21:dateStamp>
<ax21:html>adsasdasdsadasd</ax21:html>
<ax21:pdsReference />
<ax21:product>AVi (Exterior AND Interior Inspection) - 48hr RUSH</ax21:product>
<ax21:sourceData />
<ax21:successful>true</ax21:successful>
<ax21:value>168000.0</ax21:value>
</ns:return>
</ns:getReportTestResponse>
</soapenv:Body>
</soapenv:Envelope

Tried simplexml_load_string and comes back with nothing. Any help would be great thanks.

Create a Menu and Select Details for each link

$
0
0

Hello All

 

From the begin i have the following code.

<?php
$sql = "SELECT id,phonemodel FROM iphone";
$rows = $conn->sqlExec($sql);

$nr_row = $conn->num_rows;
$meniu ='<ul>';
if($nr_row>=0) {
  foreach($rows as $row) {
     $meniu .= '<li><a href="iphone.php?id='.$row['id'].'">'.$row['phonemodel'].'</a></li>';
	 }
  }
  $meniu .= '</ul>';
  
  echo $meniu;
	 
	 if(isset($_GET['id'])) {
	    $id =  (int)$_GET['id'];
		$sql = "SELECT * FROM iphone WHERE  id = $id";
$rows = $conn->sqlExec($sql);

$nr_rows = $conn->num_rows;
if($nr_rows>0) {
  foreach($rows as $row){
   echo 'Name Tel: '.$row["phonemodel"].' Title : '.$row["titlereparation"].' 
   Pret : '.$row["price"].' Message : '.$row["msj"].' ID : '.$row["id"].'<br />';
   }
  }
  else {
  echo '0 Results';
  }
}
?> 

Basicaly i have a website for phone repairs.And i want to create in iphone.php a menu from DB and when i acces the menu with _GET variable, when i press Iphone 5s (iphone.php?id=id page) the code have to display to me,all reparations for iphone 5s.

Until now,i succssed to create the Menu but the code keep add same line in the menu when i add for example a second reparation for 5s.And i don't know how to select all reparation for 5s and display them in a single link like above Iphone 5s (iphone.php?id=id page).

Now the script working like this.Create a menu with all phone names.

Iphone 5s Iphone 3 Iphone 3s Iphone 4 Iphone 5s Iphone 5s

Shoud be like

Iphone 5s Iphone 3 Iphone 3s Iphone 4 Other new devices..

And display the reparation in every link from list By ID.i try it to select by phone names,not working.

Any body with any ideea please?

Thx so much

Checking mime types of two files in a string

$
0
0

I'm working on a two-file upload form and want to be able to check the mime types of two filenames in a string variable.

The code below was working when the variable @resume_path contained just one filename. How can I modify this to accommodate two files?

 

when I echo $resume_path, I get, for example:  cover_letter_centerline.doc, cover_letter_ctg.doc

 

Thanks!   

    //DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
    //Check MIME Type by yourself.
     $finfo = new finfo(FILEINFO_MIME_TYPE);
     if (false === $ext = array_search(
         $finfo->file($_FILES['resume_path']['tmp_name']),
         array(
            'txt' => 'text/plain',
            'doc' => 'application/msword',
            'pdf' => 'application/pdf',
         ),
         true
     )) {
         throw new RuntimeException('Invalid file format.');
     }
     echo "Sorry, invalid file format.  Please try again.";
     echo $ext;
Viewing all 13200 articles
Browse latest View live