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

Another, sigh, "unexpected end of file" error

$
0
0

I am sure to get some flack for this, but I have searched google, and this forum, and found some great advice, but I am still getting the "unexpected end of file" error.

 

Any assistance is appreciated.

 

Background, I have an HTML form that submits an email to me and I would also like to send the form data to a DB.

 

The emailform.php has the include ("loaddb.php"); at the top. The emailform.php works fine, but the data never gets entered into the DB.

<?php

$servername = “localhost”;
$username = “”;
$password = “”;
$dbname = “”;
$tblname = “”;

If (isset($_POST[‘submit’]))
	{
		$conn = mysqli_connect($servername, $username, $password);

		if (!$conn)
	{
		die('Could not connect: ' . mysqli_error());
	}
		mysqli_select_db($dbname, $conn);

		$first_name = $_POST['first_name'];
		$last_name = $_POST['last_name'];
		$email_from = $_POST['email'];
		$telephone = $_POST['telephone'];


		$first_name = mysqli_real_escape_string($first_name);
		$last_name = mysqli_real_escape_string($last_name);
		$email = mysqli_real_escape_string($email);
		$telephone = mysqli_real_escape_string($telephone);

	$query = "
	INSERT INTO $dbname.$tblname(‘ID’, ‘First’, ‘Last’, ‘Email’, ‘Phone’)
	VALUES (NULL, '$first_name', '$last_name', '$email', '$telephone');”;
        }

	mysqli_close($conn);

?>

I checked whitespace, all brackets appear to be closing. Error shows as last line with the closing "?>" and I am stumped.

 

Again, sorry for "another one of these error" questions but I just cannot get this to work and have been trying everything I can think of.


Creating 'count' function as training - problem with multidimensional arrays

$
0
0

hi ho!
I'm rookie and wanna create count function from zero as training (just to learn some stuff about arrays). What I got:
 

<?
	$menu = array (
		array('link'=>'Magic', 'href'=>'9.php'),
		array('link'=>'Poker', 'href'=>'10.php'),
		array('link'=>'Number', 'href'=>'11.php'),
		array('link'=>'Count', 'href'=>'12.php'),
		array('link'=>'Size', 'href'=>'13.php')
	);

function myCount ($count, $mode=0) { // mode - if it would be multidimensional array
	if (is_array($count)){
			$b=0; // if array would be empty
			foreach ($count as $a) {
					if (is_array($a) and $mode==1)
					$b += myCount($a, 1);
				$b++;
			}
	} elseif (is_null($count)){
	$b = 0;
	} else {
	$b = 1;
	}
print "$b";
}

myCount ($menu, 1);

?>

It counts normal arrays ok, but it counts too much with multidimensional. To count them I'm making recursion, but it seems it doesn't work corrent; aswer is '222225' lol :D

 

Please help! :)

New To Php/MYSQLi

$
0
0

Hi PHP'ers

 

Working on learning as much as I can and thought I would try to make a little chat program. 

 

I have 4 main files. 

 

index.php

<?php
	require ('db/connect.db.php');

	if(isset($_POST['send'])){
		if (send_msg($_POST['sender'], $_POST['message'])){
			echo "Message Sent";
		} else {
			echo "Message Failed To Send";
		}
	}

?>

<div id="messages">
<?php
$messages = get_msg();
foreach ($message as $message) {
	echo $message['sender']."Sent<br>";
	echo $message['message']."<br>";
}
?>
</div>
<form action="index.php" method="post">
<labal>Enter Name: <input type="text" name="sender"></labal>
<label>Enter Message:<input type="text" name="message"></label>
<input type="submit" name="send" value="Send Message">
</form>

chat.func.php

<?php

	function get_msg(){
		$query = "SELECT 'sender','Message' FROM 'chat'.'chat'";

		$run = mysqli_query($query);

		$message = arrary();

		while($message = mysqli_fetch_assoc($run)) {
			$message[] =array('sender'=>$message['Sender'],
							  'message'=>$message['Message']);
		}
		return $messages;
	}

	function send_msg($sender, $message) {
		if(!empty($sender) && !empty($message)){

			$sender = mysqli_real_escape_string($sender);
			$message = mysqli_real_escape_string($message);

			$query = "INSERT INTO 'chat'. 'chat' VALUES(null, '{$sender}', '$message') ";

			if($run = mysqli_query($query)) {
				return true;
			} else {
				return false;
			}

		} else {
			return false;
		}
	}


 ?>

core.inc.php

<?php

	require ('db/connect.db.php');
	require ('function/chat.func.php');



 ?>

and final connect.db.php

<?php

	$servername = "localhost";
	$username = "root";
	$password = "";
	$dbname = "chat";

	$conn = new mysqli($servername,$username,$password,$dbname);

	if ($conn) {
		echo "Connection Success";
	} else {
		echo "Connection Failed:" . mysql_errno();
	}
?>

When I try to run the script I get the following error

 

Fatal error: Uncaught Error: Call to undefined function get_msg() in C:\xampp\htdocs\ChatAPP\index.php:16 Stack trace: #0 {main} thrown in C:\xampp\htdocs\ChatAPP\index.php on line 16

 

I am not 100% sure what I have done. Should I not have this as a function or is it more than that. 

 

Please help when you can. 

 

Thank you,

Sean

Compressing JSON options

Fatal error: Uncaught TypeError: sha1() expects parameter 1 to be string, integer given

$
0
0

Guys,

 

Even though my Sha1 has string, I get this error:

 

Fatal error: Uncaught TypeError: sha1() expects parameter 1 to be string, integer given in C:\xampp\htdocs\id\register.php:31 Stack trace: #0 C:\xampp\htdocs\id\register.php(31): sha1(16) #1 {main} thrown in C:\xampp\htdocs\id\register.php on line 31

 

<?php
 
/*
ERROR HANDLING
*/
declare(strict_types=1);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
 
include 'config.php';
 
// check if user is already logged in
if (is_logged() === true) {
die("You are already logged-in! No need to register again!");
}
 
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if (isset($_POST["username"]) && 
  isset($_POST["password"]) &&
  isset($_POST["password_confirmation"]) && 
  isset($_POST["email"]) && 
  isset($_POST["email_confirmation"]) && 
  isset($_POST["first_name"]) && 
  isset($_POST["gender"]) &&
  isset($_POST["surname"])) {
 
// create random hash for email confirmation
   $account_activation_code = sha1(mt_rand(5, 30));
$account_activation_link = "http://www.".$site_domain."/".$social_network_name."/activate_account.php?email=".$_POST['email']."&account_activation_code=".$account_activation_code."";
 
    // remove space in start of string
    /*
* passwords and email are leaved unescaped here because
* if you put them into mysqli_real_escape_string they are not empty
    */
        $username  = trim(mysqli_real_escape_string($conn, $_POST["username"]));
$password  = $_POST["password"];
$password2  = $_POST["password_confirmation"];
        $first_name = trim(mysqli_real_escape_string($conn, $_POST["first_name"]));
        $surname  = trim(mysqli_real_escape_string($conn, $_POST["surname"]));
$gender  = trim(mysqli_real_escape_string($conn, $_POST["gender"]));
        $email  = $_POST["email"];
        $email_confirmation = $_POST["email_confirmation"];
        $email2  = trim(mysqli_real_escape_string($conn, $email)); // Escaped email for inserting into database.
        $account_activation = 0; // 1 = active | 0 = not active
 
        //Hashed Password.
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
        
//SEE IF BELOW CODE AFTER FOLLOWING WORKS OR NOT AS SUBSTITUTE FUNCTION OVER mysqli_stmt_get_result FUNCTION
//Select Username and Email to check against Mysql DB if they are already registered or not.
$stmt = mysqli_prepare($conn, "SELECT usernames, emails FROM users WHERE usernames = ? OR emails = ?");
mysqli_stmt_bind_param($stmt, 'ss', $username, $email_2);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
 
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
        
// Check if inputted Username is already registered or not.
if ($row['usernames'] == $username) {
$_SESSION['error'] = "That username is already registered.";
// Check if inputted Username is between 8 to 30 characters long or not.
} elseif (strlen($username) < 8 || strlen($username) > 30) {
$_SESSION['error'] = "Username must be between 8 to 30 characters long!";
// Check if inputted Email is already registered or not.
} elseif ($row['emails'] == $email_2) {
$_SESSION['error'] = "That email is already registered.";
// Check if both inputted EMails match or not.
} elseif ($email != $email_confirmation) {
$_SESSION['error'] = "Emails don't match!";
// Check if inputed Email is valid or not.
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$_SESSION['error'] = "Invalid email! Insert your real Email in order for us to email you your account activation details.";
// Check if both inputted Passwords match or not.
} elseif ($password != $password_confirmation) {
$_SESSION['error'] = "Passwords don't match.";
// Check if Password is between 8 to 30 characters long or not.
} elseif (strlen($password) < 8 || strlen($password) > 30) {
$_SESSION['error'] = "Password must be between 6 to 30 characters long!";
} else {
 
//Insert the user's input into Mysql database using php's sql injection prevention method.
$stmt = mysqli_prepare($conn, "INSERT INTO users(usernames, passwords, emails, first_names, surnames, genders, accounts_activations_codes, accounts_activations) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'sssssssi', $username, $hashed_password, $email2, $first_name, $surname, $gender, $account_activation_code, $account_activation);
mysqli_stmt_execute($stmt);
 
//Check if user's registration data was successful submitted or not.
if (mysqli_stmt_insert_id($stmt)) {
echo "<h3 style='text-align:center'>Thank you for your registration!<br /> Check your email for details on how to activate your account you just registered.</h3>";
 
//Send account activation link by email for user to confirm his email and activate his new account.
$to = $email;
$subject = "Your ".$site_name." account activation!";
$body  = nl2br("
===============================\r\n
".$site_name." \r\n
===============================\r\n
From: ".$site_admin_email."\r\n
To: ".$email."\r\n
Subject: Yours ".$subject." account activation \r\n
Message: ".$first_name." ".$surname."\r\n You need to click on following <a href=".$account_activation_link.">link</a> to activate your account by confirming your email address. \r\n");
$headers = "From: " . $site_admin_email . "\r\n";
 
   if (mail($to,$subject,$body,$headers)) {
    $_SESSION['error'] = "Registration sucessful! Check your email for further instructions!";
 
//Clear the Session Error so it can no longer be used.
unset($_SESSION['error']);
unset($_POST);
exit();
 
//Redirect user to login page after 5 seconds.
header("refresh:5;url=login.php");
   } 
else 
{
    $_SESSION['error'] = "Email not sent, please contact website administrator!";
   }     
} 
else 
{
$_SESSION['error'] = "There was a problem in trying to register you! Try again some other time.";
}
   }
}
}
 
?>
<!DOCTYPE html>
<html>
<head>
<title><?php $social_network_name ?> Signup Page</title>
</head>
<body>
<div class ="container">
 
<?php
 
// error messages
if (isset($_SESSION['error']) && !empty($_SESSION['error'])) {
echo '<p style="color:red;">'.$_SESSION['error'].'</p>';
}
 
?>
 
<form method="post" action="">
<center><h2>Signup Form</h2></center>
<div class="form-group">
<center><label>Username:</label>
<input type="text" placeholder="Enter a unique Username" name="username" required [A-Za-z0-9] value="<?php if(isset($_POST['username'])) { echo htmlentities($_POST['username']); }?>"></center>
</div>
<div class="form-group">
<center><label>Password:</label>
<input type="password" placeholder="Enter a new Password" name="password" required [A-Za-z0-9]></center>
</div>
<div class="form-group">
<center><label>Repeat Password:</label>
<input type="password" placeholder="Repeat a new Password" name="password_confirmation" required [A-Za-z0-9]></center>
</div>
<div class="form-group">
<center><label>First Name:</label>
<input type="text" placeholder="Enter your First Name" name="first_name" required [A-Za-z] value="<?php if(isset($_POST['first_name'])) { echo htmlentities($_POST['first_name']); }?>"></center>
</div>
<div class="form-group">
<center><label>Surname:</label>
<input type="text" placeholder="Enter your Surname" name="surname" required [A-Za-z] value="<?php if(isset($_POST['surname'])) { echo htmlentities($_POST['surname']); }?>"></center>
</div>
<div class="form-group">
<center><label>Gender:</label>
<input type="radio" name="gender" value="male" <?php if(isset($_POST['gender'])) { echo 'checked'; }?> required>Male<input type="radio" name="gender" value="female" <?php if(isset($_POST['gender'])) { echo 'checked'; }?> required>Female</center>
</div>
<div class="form-group">
<center><label>Email:</label>
<input type="email" placeholder="Enter your Email" name="email" required [A-Za-z0-9] value="<?php if(isset($_POST['email'])) { echo htmlentities($_POST['email']); }?>"></center>
</div>
<div class="form-group">
<center><label>Repeat Email:</label>
<input type="email" placeholder="Repeat your Email" name="email_confirmation" required [A-Za-z0-9] value="<?php if(isset($_POST['email_confirmation'])) { echo htmlentities($_POST['email_confirmation']); }?>"></center>
</div>
<center><button type="submit" class="btn btn-default" name="submit">Register!</button></center>
<center><font color="red" size="3"><b>Already have an account ?</b><br><a href="login.php">Login here!</a></font></center>
 
</form>
 
</div>
</body>
</html>

How to display image from mysql BLOB data type using PHP

$
0
0

Hi 

I am new. I am using Bootstrap css.

I have an issue to display image with data type BLOB, Really I don't know how to do this. 

Pls advise me how to do this.

Thanks

maideen

 

My php insert Code

<?php
require_once '../inc/config.php';

if(isset($_POST['add']))
{
    if($_SERVER["REQUEST_METHOD"] == "POST")
    {

      $sid =$_POST['sid'];
      $sname =$_POST['sname'];
      $nric=$_POST['nric'];
      $gender=$_POST['gender'];
      $dob=$_POST['dob'];
      $courseid=$_POST['courseid'];
      $pname=$_POST['pname'];
      $emailid=$_POST['emailid'];
      $hpno=$_POST['hpno'];
      $homeno=$_POST['homeno'];
      $offno=$_POST['offno'];
      $emergencyno=$_POST['emergencyno'];
      $address=$_POST['address'];
      $city=$_POST['city'];
      $state=$_POST['state'];
      $country=$_POST['country'];
      $hname=$_POST['hname'];
      $alergies=$_POST['alergies'];
      $milkpowder=$_POST['milkpowder'];
      $specialfoods=$_POST['specialfoods'];
      $specactivy1=$_POST['specactivy1'];
      $specactivy2=$_POST['specactivy2'];
      $specactivy3=$_POST['specactivy3'];
      $specactivy4=$_POST['specactivy4'];
      $simage=$_POST['simage'];
      $createdby =$_POST['username'];
      $time = strftime("%X");
      $date = strftime("%B %d,%Y");
      //$createdon= $date;
      $createdon = date("Y-m-d H:i:s");
      $bool = true;
      $sql="insert into tbl_student_master(sid,sname,nric,gender,dob,courseid,pname,emailid,hpno,homeno,offno,emergencyno,address,city,state,country,hname,alergies,milkpowder,
            specialfoods,specactivy1,specactivy2,specactivy3,specactivy4,simage,createdby,createdon)
            values ('$sid','$sname','$nric','$gender','$dob','$courseid','$pname','$emailid','$hpno','$homeno','$offno','$emergencyno','$address','$city','$state','$country',
                    '$hname','$alergies','$milkpowder','$specialfoods','$specactivy1','$specactivy2','$specactivy3','$specactivy4','$simage','$createdby','$createdon')";
      $stmt=$pdo->prepare($sql);
      $stmt->execute();
      $pdo = null;
      print '<script>alert("Saved");</script>';
      header("location:../student/student_add.php");
    }
}

Insert HTML

                        <div class="col-md-9">
                            <div class="fileinput fileinput-new" data-provides="fileinput">
                                <div class="fileinput-new thumbnail" style="width: 200px; height: 150px;">
                                    <img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&text=no+image" alt="" /> </div>
                                <div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 150px;"> </div>
                                <div>
                                    <span class="btn default btn-file">
                                        <span class="fileinput-new"> Select image </span>
                                        <span class="fileinput-exists"> Change </span>
                                        <input type="file" name="simage"> </span>
                                    <a href="javascript:;" class="btn red fileinput-exists" data-dismiss="fileinput"> Remove </a>
                                </div>
                            </div>
                        </div>

 My display php code

<?php

if($_SERVER["REQUEST_METHOD"] == "GET")
    {
        $id=$_GET['id'];
        $sql ="Select * from tbl_student_master where id ='$id'";
        $stmt = $pdo->prepare($sql);
        $stmt->execute();
            while ($row = $stmt->fetch())
            {
              $id =$row['id'];
              $sid =$row['sid'];
              $sname =$row['sname'];
              $nric=$row['nric'];
              $gender=$row['gender'];
              $dob=$row['dob'];
              $courseid=$row['courseid'];
              $pname=$row['pname'];
              $emailid=$row['emailid'];
              $hpno=$row['hpno'];
              $homeno=$row['homeno'];
              $offno=$row['offno'];
              $emergencyno=$row['emergencyno'];
              $address=$row['address'];
              $city=$row['city'];
              $state=$row['state'];
              $country=$row['country'];
              $hname=$row['hname'];
              $alergies=$row['alergies'];
              $milkpowder=$row['milkpowder'];
              $specialfoods=$row['specialfoods'];
              $specactivy1=$row['specactivy1'];
              $specactivy2=$row['specactivy2'];
              $specactivy3=$row['specactivy3'];
              $specactivy4=$row['specactivy4'];
              $simage=$row['simage'];
            }
    }

?>

My Display HTML

                        <div class="col-md-9">
                            <div class="fileinput fileinput-new" data-provides="fileinput">
                                <div class="fileinput-new thumbnail" style="width: 200px; height: 150px;">
                                    <img src="" alt=""  />
                                    <?php echo $simage; ?>
                                </div>
                                <div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 150px;"></div>
                                <div>
                                    <span class="btn default btn-file">
                                        <span class="fileinput-new"> Select image </span>
                                        <span class="fileinput-exists"> Change </span>
                                        <input type="file" name="simage"> </span>
                                    <a href="javascript:;" class="btn red fileinput-exists" data-dismiss="fileinput"> Remove </a>
                                </div>
                            </div>
                        </div>

Can you help out a beginner?

$
0
0

Hey guys

 

I really hope that you could help out a beginner here. I have two questions that I hope you could answer.

 

I have made a page that contains a sign up function, a log in function, and a comment section.

Its very basic PHP. I want registered users to be able to leave comments, and I as an admin would like to be able to manage the user information at the front-end.

 

I have a database called loginsystem, which contain two tables. "users" and "comments"

 

comments table:

 

cid

uid

date

message

 

user table

 

user_id

user_first

user_last

user_email

user_uid

user_pwd

 

PROBLEM 1

 

I want to be able to display the username in the comments inside my main.php page.

<?php
    date_default_timezone_get('Europe/Copenhagen');
	include_once 'header.php';
    include 'dbh.inc.php';
    include 'comments.inc.php';
    include '/login.inc.php'
?>

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link href="comments.css" rel="stylesheet" type="text/css">
</head>

<body>


<video width="320" height="240" controls>
  <source src="movie.mp4" type="video/mp4">
  <source src="movie.ogg" type="video/ogg">
</video>

<?php
        if (isset($_SESSION['u_id'])) {
echo
"<form method='POST' action='".setComments($conn)."'>
<input type='hidden' name='uid' value='".$_SESSION['u_id']."'>
<input type='hidden' name='date' value='".date('Y-m-d H:i:s')."'>
	<textarea name='message'></textarea><br>
	<button type='submit' name='commentSubmit'>Comment</button>
</form>";
    } else {
        echo "You need to be logged in to comment";
    }
	getComments($conn);
?>
</body>

<?php
	include_once 'footer.php';
?>

So far I have only been able to change it, so that when a user posts, the username will be shown as a number.

 

<?php
        if (isset($_SESSION['u_id'])) {
echo
"<form method='POST' action='".setComments($conn)."'>
<input type='hidden' name='uid' value='".$_SESSION['u_id']."'>
<input type='hidden' name='date' value='".date('Y-m-d H:i:s')."'>
<textarea name='message'></textarea><br>
<button type='submit' name='commentSubmit'>Comment</button>
</form>";
    } else {
        echo "You need to be logged in to comment";
    }
getComments($conn);
?>

 

I know the next step is to change something in the function inside the file comments.inc.php, but I have no idea what.

<?php

function setComments($conn) {
	if (isset($_POST['commentSubmit'])) {
		$uid = $_POST['uid'];
		$date = $_POST['date'];
		$message = $_POST['message'];

		$sql = "INSERT INTO comments (uid, date, message)
		VALUES ('$uid', '$date', '$message')";
		$result = mysqli_query($conn, $sql);
	}
}

function getComments($conn) {
	$sql = "SELECT * FROM comments order by cid desc";
	$result = mysqli_query($conn, $sql);
	while ($row = $result->fetch_assoc()) {
	 echo "<div class='comment-box'><p>";
		echo $row['uid']."<br>";
		echo $row['date']."<br>";
		echo nl2br($row['message']);
	 echo "</p>

	 <form class='delete-form' method='POST' action='".deleteComments($conn)."'>

	 <input type='hidden' name='cid' value='".$row['cid']."'>
	 <button type='submit' name='commentDelete'>Delete</button>

	 </form>

	 <form class='edit-form' method='POST' action='editcomment.php'>

	 <input type='hidden' name='cid' value='".$row['cid']."'>
	 <input type='hidden' name='uid' value='".$row['uid']."'>
	 <input type='hidden' name='date' value='".$row['date']."'>
	 <input type='hidden' name='message' value='".$row['message']."'>
	 <button>Edit</button>

	 </form>

	 </div>";

	}
}

function editComments($conn) {
	if (isset($_POST['commentSubmit'])) {
		$cid = $_POST['cid'];
		$uid = $_POST['uid'];
		$date = $_POST['date'];
		$message = $_POST['message'];

		$sql = "UPDATE comments SET message='$message' WHERE cid='$cid'";
        $result = mysqli_query($conn, $sql);
		header("location: main.php");

	}
}

function deleteComments($conn) {
		if (isset($_POST['commentDelete'])) {
		$cid = $_POST['cid'];

		$sql = "DELETE FROM comments WHERE cid='$cid'";
        $result = mysqli_query($conn, $sql);
		header("location: main.php");

	}
}

PROBLEM 2
 
I have created an admin page, following a CRUD tutorial, and I have created the php file, where I want to access the user data and make changes to it or delete it.
The problem is that I am getting the error PHP Notice: Trying to get property of non-object in C:\MAMP\htdocs\php44\admin.php on line 34
 
<?php require_once 'dbh.inc.php'; ?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link   href="css/bootstrap.min.css" rel="stylesheet">
    <script src="js/bootstrap.min.js"></script>
</head>

<body>
    <div class="container">
            <div class="row">
                <h3>PHP CRUD Grid</h3>
            </div>
            <div class="row">
                <p>
                    <a href="create.php" class="btn btn-success">Create</a>
                </p>
                <table class="table table-striped table-bordered">
                  <thead>
                    <tr>
                      <th>User ID</th>
                      <th>First name</th>
                      <th>Last name</th>
                      <th>Email Address</th>
                    </tr>
                  </thead>
                  <tbody>
                      <?php
            $sql = "SELECT * FROM users WHERE active = 1";
            $result = mysqli_query($conn, $sql);

            if($result->num_rows > 0) {
                while($row = $result->fetch_assoc()) {
                    echo "<tr>
                        <td>".$row['user_id']." </td>
                        <td>".$row['user_first']." </td>
                        <td>".$row['user_last']."</td>
                        <td>".$row['user_email']."</td>
                        <td>
                            <a href='edit.php?id=".$row['id']."'><button type='button'>Edit</button></a>
                            <a href='remove.php?id=".$row['id']."'><button type='button'>Remove</button></a>
                        </td>
                    </tr>";
                }
            } else {
                echo "<tr><td colspan='5'><center>No Data Avaliable</center></td></tr>";
            }
            ?>
                  </tbody>
            </table>
        </div>
    </div> <!-- /container -->
  </body>
</html>

 

 

This is probably easy for you guys, but I am completely lost.

I would appreciate if you could explain to me what I have done wrong. I have added the files as well.

Attached Files

Prepared statement in a function

$
0
0

I will be performing a query multiple times and for readability and/or code reduction wish to perform the query in a function.

 

Anything wrong with the following?  Originally, I was thinking of saving the prepared statement in $this->stmt, but then multiple instances of  MyClass would have their own prepared statement which doesn't seem like a big deal but I see no reason why necessary.  Any more recommended way to do so?

 

Thanks

class MyClass
{
    public function getSomeData($id)
    {
        static $stmt;
        if(!$stmt) $stmt=$this->db->prepare('SELECT a,b,c from t WHERE id=?');
        $stmt->execute($id);
        $rs=[];
        while($record = $stmt->fetch()) {
            //manipulate data as necessary
            $rs[]=$record;
        }
        return $rs;
    }
}

 

EDIT.  I know this won't work as is (trying to get it before the edit time expires!), but is something like this possible where the second function returns one result at a time? EDIT 2.  Guess I should just use return fetchAll();

 

class MyClass
{
    public function other($id)
    {
        while($record = $this->getSomeData($id) {
            //manipulate data as necessary
            $rs[]=$record;
        }
        return $rs;
    }


    private function getSomeData($id)
    {
        static $stmt;
        if(!$stmt) $stmt=$this->db->prepare('SELECT a,b,c from t WHERE id=?');
        $stmt->execute($id);
        return $stmt->fetch();
    }
}

Beginner PHP and need some help please, thank you :)

$
0
0
Hi
 
Beginner with PHP, I am making some changes to an application that was written by someone else. Very little documentation at all, so I'm navigating the 
 
code.
 
 
The portion that I need help with is this - we are currently using a drop down where they choose one option.  We need to change it to be checkboxes where  they can select as many options as they'd like. I'm sharing the 3 main functions that are related to the task at hand.  These functions were spread out over  3 different files, each having 1,000+ lines of code. So I'm a bit overwhelmed to say the least.
 
Thanks so much in advance for your assistance.  Will be checking back frequently in case I have left anything out in order to get help.
You guys rock! Thank you
 
 
function rrComponentFields($pre, $component, $loc){
global $locationObj;
 
$dbType = utilities::getDBtype($pre);
 
$outStr = "<select class='input-box' name='{$pre}Conponent' id='{$pre}Conponent' onchange='getConponentDetails(\"$pre\");>";
 
$gct = $locationObj->getCleanableTargetsByType($pre, $component, $loc);
 
for( $i=0; $i<count($gct); $i++ ){
$row = $gct[$i];
 
$isSelected = "";
 
if( $row["SELECTED"] == true ){
$isSelected = "selected=\"selected\"";
}
 
$outStr .= "<option value=\"$row[CTID]\" $isSelected> $row[FULLNAME] </option>";
}
 
$outStr .= "</select><input type='checkbox' name='allConponents' value='allConponents' id='{$pre}AllConponents' /> Apply to all conponents <br/>";
 
return $outStr;
}
 

function getConponentDetails(pre){
/*switch(pre){
case "pl":
case "i":
//url = "getInterlockingInfo.php";
url = "getStationInfoNoConponent.php";
break;
case "l":
default:
url = "getStationInfo.php";
break;
}
*/
var param = document.getElementById( pre+'Conponent' ).value;
 
var eventId = window.eventId;
 
if(window.XMLHttpRequest){
// If IE7, Mozilla, Safari, etc: Use native object
var client = new XMLHttpRequest();
}else{
if(window.ActiveXObject){
// ...otherwise, use the ActiveX control for IE5.x and IE6
var client = new ActiveXObject("Microsoft.XMLHTTP");
}
}
     
 
//getEmployees(pre);
 
client.onreadystatechange = function() {conponentDetailhandler(pre, client)};
client.open("GET", "getStationInfo.php" + "?param=" + param + "&eventId=" + eventId);
client.send("");
} //getData()
 
 
 
function conponentDetailhandler(pre, obj) {
console.log( "Pre = ", pre );
 
var status = document.getElementById(pre+'Status');
 
var comments = document.getElementById(pre+'History');
 
var forman = document.getElementById(pre+'Forman');
 
var pass = document.getElementById(pre+'PassNum');
//var bags = document.getElementById(pre+'NumBags');
 
var gangButton = document.getElementById('gangEnterUpdate');
 
var downloadFile = document.getElementById(pre+'DownloadFile');
downloadFile.options.length = 0;
 
if(obj.readyState == 4 && obj.status == 200) {
var val = eval('(' + obj.responseText + ')');
 
for(var i = 0; i < val.length; i++) {
var txtNew = document.createElement('text');
 
txtNew.text = val[i].STATUS;
status.value = txtNew.text;
 
txtNew.text = val[i].COMMENTS;
comments.value = txtNew.text;
 
txtNew.text = val[i].PASS;
 
if(pass){
pass.value = txtNew.text;
}
 
 
var doctxt = txtNew.text;
 
//-------------------------------
//Grab all the attached documents and list in a option
txtNew.text = val[i].SUPPORTDOCS;
 
var doctxt = txtNew.text;
 
var docArray = new Array();
 
if(doctxt && doctxt.length > 0){
docArray = doctxt.split(",");
}
 
for(var x = 0; x < docArray.length; x++) {
var opt = docArray[x];
var el = document.createElement("option");
 
el.innerHTML = opt;
el.value = opt;
downloadFile.appendChild(el);
}

Emails are being combined

$
0
0

Hey again, hopefully this is a bit less beginner than my previous issue but I will likely find out not.

 

I am writing a php page to send an email reminder to a list in a MySQL database. I want two separate email messages based on whether two of the columns in the database are yes/yes or the second email message if yes/no and no email message if yes/(yes or no). This is not the issue as I have the following in two separate parts of php.

 

This is appropriately selecting which 'users' to send emails to and which message.

 

Right now I am only testing the DB and don't have any real data loaded yet.

 

My issue is when I have 2+ users with the same set up combination (Yes/Yes) or (Yes/No) that the email message is 1) same message is being sent to both emails 2) the messages are being combined

 

Example

User 1 - email

Hi User 1,

Welcome to the web

From Me

Hi User 2,

Welcome to the web

From Me

 

User 2 - email

Hi User 1,

Welcome to the web

From Me

Hi User 2,

Welcome to the web

From Me

 

 

I can't figure out how to separate the messages to the different users and ensure the right information is sent to the right user.

<?php

$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$tblname = "";

        $conn = mysqli_connect($servername, $username, $password, $dbname) or die("Unable to Connect to '$dbhost' -
Please email support@domain.com");

    $sql = "SELECT * FROM $tblname WHERE item1='No' AND item2='Yes'";
    $result = mysqli_query ($conn, $sql)
    or die ('Error querying database. 1');

   while($row = mysqli_fetch_array($result)){
        $first_name = $row['First'];
        $last_name = $row['Last'];
        $stuff1 = $row['Stuff1'];
        $stuff2 = $row['Stuff2'];
        $stuff3 = $row['Stuff3'];
        $email_to = $row['Email'];

    $email_from = "support@domain.com";
    $email_subject = "Subject 1";
    $email_message .= "Hello $first_name $last_name,\n";
    $email_message .= "\n";
    $email_message .= "Message\n";
    $email_message .= "\n";
    $email_message .= "Message\n";
    $email_message .= "\n";
    $email_message .= "Message\n";
    $email_message .= "\n";
    $email_message .= "Message\n";
    $email_message .= "Message\n";

// create email headers
mail($email_to, $email_subject, $email_message, 'From:' . $email_from);
echo 'Email sent to: ' . $email_to. '<br>';


}
mysqli_close($conn);

?>

<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$tblname = "";

        $conn = mysqli_connect($servername, $username, $password, $dbname) or die("Unable to Connect to '$dbhost' - Please email support@domain.com");

    $sql = "SELECT * FROM $tblname WHERE item1='Yes' AND item2='Yes'";
    $result = mysqli_query ($conn, $sql)
    or die ('Error querying database. 2');

    while($row = mysqli_fetch_array($result)){
        $first_name2 = $row['First'];
        $last_name2 = $row['Last'];
        $stuff12 = $row['Stuff1'];
        $stuff22 = $row['Stuff2'];
        $stuff32 = $row['Stuff3'];
        $email_to2 = $row['Email'];

    $email_from = "support@domain.com";
    $email_subject2 = "Subject 2";
    $email_message2 .= "Hello $first_name2 $last_name2,\n";
    $email_message2 .= "\n";
    $email_message2 .= "Message2\n";
    $email_message2 .= "\n";
    $email_message2 .= "Message2\n";
    $email_message2 .= "\n";
    $email_message2 .= "Message2\n";
    $email_message2 .= "\n";
    $email_message2 .= "Message2\n";
    $email_message2 .= "Message2\n";

// create email headers
mail($email_to2, $email_subject2, $email_message2, 'From:' . $email_from);
echo 'Email sent to: ' . $email_to2. '<br>';

}
mysqli_close($conn);
?>

Displaying multiple error messages

$
0
0

hi i need that when i putt submit  empty message will writen in each field if empty firstname write down firstname, thank you

if (isset($_POST['submit'])) {
    function validate($key, $value)
    {
        $error = false;
        switch ($key) {
            case 'firstname':
                if (empty($value)) {
                    $error = 'Putt Your Firstname';
                }
                break;
            case 'lastname' :
                if (empty($value)) {
                    $error = 'Putt Your Lastname';
                }
                break;
            case 'email':
                if (empty($value)) {
                    $error = 'Putt Your Email';
                }
                break;
            case 'pass' :
                if (empty($value)) {
                    $error = 'Putt Your Password';
                }
                break;
            case 'confirmpass' :
                if (empty($value)) {
                    $error = 'Putt Your Confirmpassword ';
                }
        }
        return $error;
    }
 
    // $arr = array('firstname', 'lastname', 'email', 'pass', 'confirmpass');
 
    foreach ($_POST as $key => $value) {
        $error = validate($key, $value);
        // echo $error;
    }
}

One submit button , Two actions

$
0
0

Requirement:

 

I have a drupal website, wherein i have to use single form for two purpose.

1) Send lead source(which is a parameter) to Salesforce Platform:

that is one url: say for eg: https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8

 

2) Send the same form values to another URL which is actually for sign up on Salesforce Platform:

"same form values are used by salesforce to email the user, so that he can sign up, that's a different story"

this is second url: say for eg: http://www.salesforce.com/leadcapture/PartnerSignupServlet

 

Difficulty:

Now i have one form. but when user submits the form it has to go to both URLs which is actually not happening.

 

 

Please help me with this.

 

 

 

getting data from multiple tables with sum in a single result set

$
0
0

Hi,

 

I am trying to get the income-expense report on month basis. Actually for income, i am getting data from 'receipt' table structure is like this

 

recceipt.PNG

 

But for expense, i have to get the data from 2 tables, 'payments' and 'expense' , like this

 

payments.PNG

expense.PNG

 

My display should be like this

 

data.PNG

 

Actually for only 2 tables i got the result in the same format. Here is the working query

$sqlm = "SELECT r.invoice_id, r.customer, r.paid_amount, r.mode, r.ref_no, MONTHNAME(r.paid_date) AS 'Month', YEAR(r.paid_date) AS Yr,  r.comments, l.company, 'Income' AS 'Income' FROM receipt r INNER JOIN leads l ON r.customer=l.id GROUP BY MONTH(r.paid_date)
UNION ALL
SELECT p.invoice_id, p.vendor, p.paid_amount, p.mode, p.ref_no, MONTHNAME(p.paid_date) AS 'Month', YEAR(p.paid_date) AS Yr, p.comments, v.name, 'Expense' AS 'Income' FROM payments p INNER JOIN vendor v ON p.vendor=v.id GROUP BY MONTH(p.paid_date) ORDER BY Yr DESC
";
$query = mysqli_query($con, $sqlm)
?>
<table>
<tr><th>Paid Amount</th>
<th>Details</th>
<th>Month</th>
</tr>
<?php while($row = mysqli_fetch_array($query)) {
?>
<tr>
<td><?php echo $row['paid_amount']; ?></td>
<td><?php echo $row['Income']; ?></td>
<td><?php echo $row['Month']; ?></td>
</tr>
<?php } ?>
</table>


But only for expense i should add 2 tables data, which i am not getting. Can somebody guide me on this?

SQL DB Sending old results

$
0
0

I am creating a website which uses a mysql database.

Which holds user information and there balance.

 

When a user purchases tokens (via Stripe) They are redirected back to the account management page.

 

I have checked stripe and they have confirmed the payment.

 

I have checked the sql database and the token value has been added.

 

But on the management page the token value is still the same.

 

(cacheing has been disabled.) Here is the code: 

            <?php

                $query = $conn->prepare("SELECT ID, username, fname, lname, email, tokens FROM `users` WHERE ID = ?");
                $query->bind_param("s",$_SESSION['ID']);
                $query->execute();
                $query->bind_result($ID, $username, $firstname, $lastname, $email, $tokens);
                $query->fetch();
                $query->close();
            ?>
            <p class="my-account-p-padded">

                <br>
                Username: <?php echo $username; ?><br>
                First Name: <?php echo $firstname; ?><br>
                Last Name: <?php echo $lastname; ?><br>
                Account Tokens: <?php echo $tokens; ?> <a href="javascript:void(0)" onclick="showlightbox();" id="addmoretokensbtn">Add More</a><br>
                <span id="explain" style="display: none;">(Scroll Up to see screen)</span>

            </p>

Screenshot of db: 

Attached.

 

Screenshot of Page:

Attached.

Attached Thumbnails

  • dbprob.PNG
  • webprob.PNG

Errors with PHP7 include statement

$
0
0

I just changed my MAMP stack to from PHP5 to PHP7

 

Now I get an error from:

 

include 'dbconfig.php';

 

If I change it to

 

include dbconfig.php;

 

it works, but I see nothing in the PHP7 documentation that says that single quotes should not be in the include line. I can take out the quotes in my code, but this will require hundreds if not thousands of edits and I am afraid that the code will no longer work on PHP5.

 

Any thoughts?


Help really needed please

$
0
0

Hi there people

 

I am in some bit of a situtation..

 

I need to be able to create a URL that redirects to an ip, however i need the url to have username and password that will transfer to the ip.

 

Basically i want to give out the url to each user and for them to type there username/password at the end

 

example

http://url.goeshere.co.uk/username/password

 

USER1 - http://url.goeshere.co.uk/user1/pass1

USER2 - http://url.goeshere.co.uk/user2/pass2

 

Both urls will then redirect to my ip and will need to be able to send the username and password also

 

example

http://my_ip:port/get.php?username=username&password=password&type=m3u&output=ts

USER1 redirects to http://my_ip:port/get.php?username=user1&password=pass1&type=m3u&output=ts

USER2 redirects to http://my_ip:port/get.php?username=user2&password=pass2&type=m3u&output=ts

 

fopen error in tcpdf

$
0
0

I am using the TCPDF library and have run into an error

	public static function fopenLocal($filename, $mode) {
		if (strpos($filename, '://') === false) {
			$filename = 'file://'.$filename;
		} elseif (stream_is_local($filename) !== true) {
			return false;
		}
		return fopen($filename, $mode);
	}

this turns my local filename: docs/filename.pdf into file://docs/filename.pdf

 

in the documentation for stream_is_local there is the comment:

 

It appears to return incorrectly for 'file://' wrapper which I would consider to be local.

CODE:

$file1 = '/somefile.jpg';
$file2 = 'file://shouldbelocal.jpg';
$file3 = 'http://someotherfile.jpg';

$local = stream_is_local($file1);
$shouldbelocal = stream_is_local($file2);
$remote = stream_is_local($file3);
var_dump($local, $shouldbelocal, $remote);

RESULT:
bool(true)
bool(false)
bool(false)

My code is getting past the stream_is_local line, so I guess it is returning true there, but it dies on the fopen line with the error:

 

fopen(file://docs/filename.pdf): failed to open stream: no suitable wrapper could be found in /Applications/mampstack-7.0.23-0/apache2/htdocs/include/tcpdf_static.php on line 1854

 

I have checked the php.ini and the line allow_url_fopen=On

 

 

Any ideas?

 

Proper way to write this conditional

$
0
0

I would like this to echo the $val['value'] if it has a value, and to display the number 0 if it does not. I have tried a few different ways of trying to get it to show 0 for the ones that have no value, but cannot seem to get both to work conditionally...Thank you


<?php
foreach($_44 as $val)
    if ($val['feat'] == '7mr') {
        echo $val['value'];
    }
?>

Using an array() from Within a Private Function Within a Class

$
0
0

Hi,

 

I've inherited some code on a system from another person. I'll be the first to admit that I'm not a PHP pro, I am self taught, and use it sparingly for personal projects mainly. So this is a bit beyond my skill level, and I was hoping for some advice:

 

The system is a glorified calendar, with a lot of our own data being slapped on top of it and presented nicely. The issue I have thoguh is that due to the way the calendar is generated, I cant make the height of the days move dynamically based on what content gets dropped into each day on the calendar. If one day is busy and has 8 events drop into it, they will overflow the days cell.

 

I wanted to adjust the height of ALL cells on a month view calendar to the heighest required height of all cells in that view.

 

What I was going to do, is +1 to a coutner for every event (or block) that is generated for each day (days are looped through a private function), and commit that number to an array. At the end fo the loop (after all days ahve been counted and have a value in the array), I was going to use max() on the array, pull the largest number, calculate the days cell hiehgt from that and apply it via CSS at page level.

 

I've summarised the code in effect here (psuedo code, not real PHP):

class Calendar {

    public $heights;

    private fucntion dayLoop($cellNumber) {
        $heights = []; //array
        $block_count = 0; //counter
        while(mysqlrowdata) {
            [code for mysql operations]
            $block_count++; //increment the count
        }
    $day_height = ($block_count * 16) + 18; //do some math specific to my application
    $this->heights[] = $day_height; //commit calc'd value to array
    //array_push($heights, $day_height); //this was a previosu attempt, i dont think i should use array_push here..??
    }
}

That function, and others is called from the front end pages to generate the calendar. If I do a:

var_dump($heights);

after it on that page, all I get returned on screen is "Array ( )"

 

I tried changing the private function to a public one, but this did not affect the outcome. Anyone have any ideas on what I'm doing wrong? Is my logic sound? Can I commit values to an array inside a loop in a public OR private function and then reference that array outside of the loop? I defined $heights as public in the class too, but that didnt change the outcome either.

 

Thanks.

file_get_contents How to target the url only with replace function ?

$
0
0
$rss = file_get_contents('www.somesite.com/rss');
$rssnew = str_replace('AAAA', 'BBB', $rss );

Hi got a sImple bit of code to replace text in the $rss,

 

how do i target the url only? as it is now its replacing all instances of "AAAA" in urls,text,links,image urls,etc.

 

 

Viewing all 13200 articles
Browse latest View live