Jump to content

Search the Community

Showing results for tags 'php'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. I am trying to centralize my database communicatin into a class (im getting tired of typing and retyping the code to send queries) Its not done but I cant get INSERT to work. Heres my Class: <?php ###################################################### # Class Name: DBConnect # Description: Base Class to handle DB inquiries # Created: 06/27/19 # Updated: 06/27/19 # Author: James 'Karæthon' Cantando # Contact: TheKaraethon@gmail.com ###################################################### class DBConnect{ ###################################################### # PROPERTIES ###################################################### # PRIVATE private const HOST = 'localhost'; private const USER = 'root'; private const PASS = ''; private const DB = 'crackthecode'; private $link; private $table; # PUBLIC ###################################################### # METHODS ###################################################### # CONSTRUCTOR function __construct($target){ $this -> table = $target; $this -> link = mysqli_connect(self::HOST,self::USER,self::PASS,self::DB); if(!$this->link){ die("An error occured while attempting to connect to the table \"{$this -> table}\" on the ".self::DB." database.<br />Error#: ".mysqli_connect_errno()."<br />Description: ".mysqli_connect_error()); } } # PRIVATE private function checkValue($val){ switch(strtoupper($val)){ case 'NULL': return 'NULL, '; break; case 'CURRENT_TIMESTAMP': return 'CURRENT_TIMESTAMP, '; break; default: return "`".$val."`, "; } } # PUBLIC public function getData($criteria){ $query = "SELECT * FROM {$this->table} WHERE "; $crit = ""; foreach($criteria as $column => $value){ if(($column === 'bind')){ $crit .= "{$value} "; }else{ $crit .= "{$column} = {$value} "; } } $result = mysqli_query($this->link, $query.$crit); if(mysqli_num_rows($result) !== 0){ return $result; }else{ return false; } } public function newData($data){ $query = "INSERT INTO `{$this->table}` "; $cols = "("; $vals = "("; foreach($data as $col => $val){ $cols .= "`".$col."`, "; $vals .= $this->checkValue($val); } $query = $query.substr($cols,0,-2).") VALUES ".substr($vals,0,-2).")"; echo $query; echo "<br />INSERT INTO `players` (`PlayerID`, `CreatedDate`, `Username`, `Passcode`, `Email`, `FName`, `Lname`, `Addr1`, `Addr2`, `City`, `State`, `Country`, `PostalCode`, `Phone`, `PhoneType`, `TaxpayerID`, `DOB`, `TokenBalance`) VALUES (NULL, CURRENT_TIMESTAMP, 'test', 'ggb', 'hyh', 'yjj', 'hjj', 'ghu', 'ghj', 'tuo', 'dgi', 'fgu', 'iyh', 'ghk', 'Other', 'tujk', '2019-6-17', '0')"; $insert = mysqli_query($this->link, $query); //$insert = mysqli_query($this->link, "INSERT INTO `players` (`PlayerID`, `CreatedDate`, `Username`, `Passcode`, `Email`, `FName`, `Lname`, `Addr1`, `Addr2`, `City`, `State`, `Country`, `PostalCode`, `Phone`, `PhoneType`, `TaxpayerID`, `DOB`, `TokenBalance`) VALUES (NULL, CURRENT_TIMESTAMP, 'test', 'ggb', 'hyh', 'yjj', 'hjj', 'ghu', 'ghj', 'tuo', 'dgi', 'fgu', 'iyh', 'ghk', 'Other', 'tujk', '2019-6-17', '0')"); if(!$insert){ echo "An error occured while attempting to INSERT into the table \"{$this -> table}\" on the ".self::DB." database.<br />Error#: ".mysqli_connect_errno()."<br />Description: ".mysqli_connect_error(); } return $insert; } ###################################################### # End Class ###################################################### } ?> The testing page has this: <?php include '../includes/dbconn.class'; $test = new DBConnect("players"); $inserted = $test->newData([ 'playerID'=> 'NULL', 'CreatedDate'=> 'CURRENT_TIMESTAMP', 'Username'=>'test', 'Passcode'=>'123456789', 'Email'=>'test@test.test', 'FName'=>'test', 'Lname'=>'tested', 'Addr1'=>'1234 msin st', 'Addr2'=>'NULL', 'City'=>'Anytown', 'State'=>'Denial', 'Country'=>'United States', 'PostalCode'=>'12345-6789', 'Phone'=>'19995551212', 'PhoneType'=>'Other', 'TaxpayerID'=>'123-45-6789', 'DOB'=>'2019-6-17', 'TokenBalance'=>'1000000000' ]); if($inserted){echo 'Insert succeeded.';}else{echo 'Insert failed.';} ?> In the class file you will see two queries, one code generated the other from a successful phpmyadmin query. The phpmyadmin one works everytime, but the generated doent. and I cant see any difference between them when echoed except the values being inserted. please what am I doing wrong? Output from echoed queries: Generated Query: INSERT INTO `players` (`playerID`, `CreatedDate`, `Username`, `Passcode`, `Email`, `FName`, `Lname`, `Addr1`, `Addr2`, `City`, `State`, `Country`, `PostalCode`, `Phone`, `PhoneType`, `TaxpayerID`, `DOB`, `TokenBalance`) VALUES (NULL, CURRENT_TIMESTAMP, `test`, `123456789`, `test@test.test`, `test`, `tested`, `1234 msin st`, NULL, `Anytown`, `Denial`, `United States`, `12345-6789`, `19995551212`, `Other`, `123-45-6789`, `2019-6-17`, `1000000000`) PHPMyAdmin Query: INSERT INTO `players` (`PlayerID`, `CreatedDate`, `Username`, `Passcode`, `Email`, `FName`, `Lname`, `Addr1`, `Addr2`, `City`, `State`, `Country`, `PostalCode`, `Phone`, `PhoneType`, `TaxpayerID`, `DOB`, `TokenBalance`) VALUES (NULL, CURRENT_TIMESTAMP, 'test', 'ggb', 'hyh', 'yjj', 'hjj', 'ghu', 'ghj', 'tuo', 'dgi', 'fgu', 'iyh', 'ghk', 'Other', 'tujk', '2019-6-17', '0') notes mysql version: 10.0.33-MariaDB (? is that correct?)
  2. So I am working with a script that allows load more scrolling, much like youtube's comments section. The script I found uses mysqli and I am using PDO. So I need a bit of help converting some code below. Origional mysqli $results = mysqli_query($connecDB,"SELECT COUNT(*) FROM paginate"); $get_total_rows = mysqli_fetch_array($results); //total records //break total records into pages $total_pages = ceil($get_total_rows[0]/$item_per_page); My PDO code $results = DB::getInstance()->query("SELECT COUNT(*) FROM guestbook"); $get_total_rows = $results->results(); //break total records into pages $total_pages = ceil($get_total_rows[0]/$item_per_page); With the code above, I get the following error. "Object of class stdClass could not be converted to int"
  3. Sorry I think my topic question is weird but just want to make the wordings as less as possible. I read a few of the threads but none of them seem to match what I need. What I'm trying to do it something like a voting system but does not include mysql at the moment. I made three radio buttons of music types pop, rock, metallic and a submit so whichever a person choose either one of them and submit the data is wrote into a data.json and stored there. Then I have a page to load all the data in data.json file but I want to count how many people selected for example metallic and how many people selected rock. at the moment I'm still testing and I actually thought of an idea but somehow searched up and not getting what I want.....can someone give me a hand? this is my data.json file {"type":"metallic"} {"type":"pop"} {"type":"metallic"} and this is what my result code is at the moment <?php $file = fopen('data.json', "r"); $array_record = array(); while(!feof($file)) { $line = fgets($file); $data = json_decode($line, TRUE); if (is_array($data)) { foreach ($data as $key => $value) { // echo $key.'='.$value.' '; // show key=value pairs $array_record += array($value,); var_dump($data); print_r($data); echo $value; } echo '<br>'.PHP_EOL; } } fclose($file); ?> I know the codes are messy because I tried setting up an empty array first then get the $value which is something like metallic into an array so I can use the array_count_values but the way I'm doing it seems totally wrong or that'd never work. I tried few other ways to get only metallic/pop so I can try counting the same thing. Thanks in advance.
  4. Hello I have this error it appears between all pages while I am navigating from one page to another, this error appears and disappears immediately, but it appears and remains present when viewing sales reports page. /*--------------------------------------------------------------*/ /* Function for checking which user level has access to the page /*--------------------------------------------------------------*/ function page_require_level($require_level){ global $session; $current_user = current_user(); $login_level = find_by_groupLevel($current_user['user_level']); //if user not login if (!$session->isUserLoggedIn(true)): $session->msg('d','Please Sign in'); redirect('index.php', false); //if Group status Deactive elseif($login_level['group_status'] === '0'): //Line 195 $session->msg('d','User Banned'); redirect('home.php',false); //checking logged in User level and Require level is Less than or equal to elseif($current_user['user_level'] <= (int)$require_level): return true; else: $session->msg("d", "Error"); redirect('home.php', false); endif; }
  5. I have created a the frontend fo the registration page in react and wrote backend in php and I have used mysql as my database This is my frontend code import React, { useState } from "react"; import "./css/Register.css"; import { Link } from "react-router-dom"; import axios from "axios"; function Register() { const [firstName, setFirstName] = useState(""); const [lastName, setLastName] = useState(""); const [email, setEmail] = useState(""); const [mobileNumber, setMobileNumber] = useState(""); const [password, setPassword] = useState(""); const [confirmPassword, setConfirmPassword] = useState(""); const [validationErrors, setValidationErrors] = useState({ emailError: "", mobileNumberError: "", passwordMatchError: "", }); const handleSubmit = (e) => { e.preventDefault(); // Email validation using regular expression const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; let newErrors = { emailError: "", mobileNumberError: "", passwordMatchError: "", }; if (!emailPattern.test(email)) { newErrors.emailError = "Please enter a valid email address"; } if (mobileNumber.length !== 10) { newErrors.mobileNumberError = "Please enter a valid mobile number"; } if (password !== confirmPassword) { newErrors.passwordMatchError = "Passwords do not match"; } if ( newErrors.emailError || newErrors.mobileNumberError || newErrors.passwordMatchError ) { setValidationErrors(newErrors); } else { setValidationErrors({ emailError: "", mobileNumberError: "", passwordMatchError: "", }); const userData = { firstName: firstName, lastName: lastName, email: email, mobileNumber: mobileNumber, password: password, }; axios.post("http://localhost:80/api/registration.php", userData); console.log(`UserData: ${JSON.stringify(userData)}`); } }; return ( <div className="register-container"> <h1 className="register-heading">Register</h1> <form onSubmit={handleSubmit} className="register-form"> <label className="register-label"> <input type="text" placeholder="First Name" value={firstName} onChange={(e) => setFirstName(e.target.value)} className="register-input" required /> </label> <br /> <label className="register-label"> <input type="text" placeholder="Last Name" value={lastName} onChange={(e) => setLastName(e.target.value)} className="register-input" required /> </label> <br /> <label className="register-label"> <input type="email" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} className="register-input" required /> </label> {validationErrors.emailError && ( <p className="register-error">{validationErrors.emailError}</p> )} <br /> <label className="register-label"> <input type="tel" placeholder="Mobile Number" value={mobileNumber} onChange={(e) => setMobileNumber(e.target.value)} className="register-input" required /> </label> {validationErrors.mobileNumberError && ( <p className="register-error">{validationErrors.mobileNumberError}</p> )} <br /> <label className="register-label"> <input type="password" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} className="register-input" required /> </label> <br /> <label className="register-label"> <input type="password" placeholder="Confirm Password" value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} className="register-input" required /> </label> {validationErrors.passwordMatchError && ( <p className="register-error"> {validationErrors.passwordMatchError} </p> )} <br /> <button type="submit" className="register-button"> Register </button> </form> <p className="register-login-link"> Already have an account? <Link to="/login">Login</Link> </p> </div> ); } export default Register; and this is my backend <?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "realestate"; header('Access-Control-Allow-Origin: http://localhost:3000'); header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE'); header('Access-Control-Allow-Headers: Content-Type'); $conn = mysqli_connect($servername, $username, $password, $dbname); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $data = json_decode(file_get_contents('php://input'), true); if (isset($data['name']) && isset($data['email']) && isset($data['mobileNumber']) && isset($data['password'])) { $name = $data['name']; $email = $data['email']; $mobileNumber = $data['mobileNumber']; $password = $data['password']; $stmt = mysqli_prepare($conn, "INSERT INTO `registration` (`name`,`email`,`mobileNumber`,`Password`) VALUES (?, ?, ?, ?)"); mysqli_stmt_bind_param($stmt, "ssss", $name, $email, $mobileNumber, $password); if (mysqli_stmt_execute($stmt)) { $response = array('status' => 'success', 'message' => 'Data stored successfully!'); } else { $response = array('status' => 'error', 'message' => 'Error: ' . mysqli_error($conn)); } mysqli_stmt_close($stmt); mysqli_close($conn); header('Content-Type: application/json'); echo json_encode($response); } ?> This is the screenshot of the table in database What is the error in the code that I have not been able to find please help me because no data is getting inserted in the database please help
  6. I have a delete button that is not working when I click on it it is showing me that error in the console I am using react for my front-end, php for my backend and mysql for my database This is the frontend code import React, { useEffect, useState } from "react"; import "./user.css"; const Buy = () => { const [buyData, setBuyData] = useState([]); const [formData, setFormData] = useState({ id: "", name: "", purpose: "", type: "", area: "", price: "", location: "", status: "", }); const [showForm, setShowForm] = useState(false); // Added state to control form visibility useEffect(() => { fetchBuyData(); }, []); const fetchBuyData = async () => { try { const response = await fetch("http://localhost:80/api/buy.php"); const data = await response.json(); setBuyData(data); } catch (error) { console.error("Error fetching buy data:", error); } }; const handleInputChange = (e) => { const { name, value } = e.target; setFormData({ ...formData, [name]: value }); }; const handleFormSubmit = async (e) => { e.preventDefault(); try { const response = await fetch(`http://localhost:80/api/buy.php`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(formData), }); const data = await response.json(); console.log("Data updated successfully:", data); fetchBuyData(); } catch (error) { console.error("Error updating buy data:", error); } }; const handleDeleteClick = async (id) => { try { const response = await fetch( `http://localhost:80/api/buydelete.php?id= `, { method: "DELETE" } ); const data = await response.json(); console.log("Data deleted successfully:", data); fetchBuyData(); } catch (error) { console.error("Error deleting buy data:", error); } }; const handleUpdateClick = (item) => { setFormData({ id: item.id, name: item.name, purpose: item.purpose, type: item.type, area: item.area, price: item.price, location: item.location, status: item.status, }); setShowForm(true); // Show form when update button is clicked }; return ( <div> <h1>Buy Page</h1> <table> <thead> <tr> <th>ID</th> <th>Name</th> <th>Purpose</th> <th>Type</th> <th>Area</th> <th>Price</th> <th>Location</th> <th>Status</th> <th>Actions</th> </tr> </thead> <tbody> {buyData.map((item) => ( <tr key={item.id}> <td>{item.id}</td> <td>{item.name}</td> <td>{item.purpose}</td> <td>{item.type}</td> <td>{item.area}</td> <td>{item.price}</td> <td>{item.location}</td> <td>{item.status}</td> <td> <button onClick={() => handleUpdateClick(item)}>Update</button> <button onClick={() => handleDeleteClick(item.id)}> Delete </button> </td> </tr> ))} </tbody> </table> {/* Form for updating data */} {showForm && ( <form onSubmit={handleFormSubmit}> <h2>Update Data</h2> <label htmlFor="name">Name</label> <input type="text" name="name" value={formData.name} onChange={handleInputChange} /> <label htmlFor="name">Purpose</label> <input type="text" name="purpose" value={formData.purpose} onChange={handleInputChange} /> <label htmlFor="type">Type</label> <input type="text" name="type" value={formData.type} onChange={handleInputChange} /> <label htmlFor="area">Area</label> <input type="text" name="area" value={formData.area} onChange={handleInputChange} /> <label htmlFor="price">Price</label> <input type="text" name="price" value={formData.price} onChange={handleInputChange} /> <label htmlFor="location">Location</label> <input type="text" name="location" value={formData.location} onChange={handleInputChange} /> <label htmlFor="status">Status</label> <input type="text" name="status" value={formData.status} onChange={handleInputChange} /> <button type="submit">Submit</button> </form> )} </div> ); }; export default Buy; And this is the back-end code <?php header('Access-Control-Allow-Origin: http://localhost:3000'); header('Access-Control-Allow-Methods: DELETE'); header('Access-Control-Allow-Headers: Content-Type'); if(isset($_POST['id'])) { $id = $_POST['id']; $conn = new mysqli('localhost', 'root', '', 'realestate1'); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $stmt = $conn->prepare("DELETE FROM property-buy WHERE id = $id"); $stmt->bind_param("i", $id); if ($stmt->execute()) { echo "Data deleted successfully"; } else { echo "Error deleting data: " . $stmt->error; } $stmt->close(); $conn->close(); } else { echo "Error: 'id' parameter is missing in the request."; } ?> And this is my database What is the problem?
  7. I use a RAD called PHPRunner to build Database Applications. One of the snippets of code I use a lot is to insert a Field Value from a Master Table into an equivalent Field in a Child Table as a "Before Add Event", is as follows: - global $dal; $tblDetail = $dal->Table("tblUserRequests"); $tblDetail->Value["ID"] = $data["ID"]; $tblDetail->Param["ID"] = $data["ID"]; $tblDetail->Update(); unset($data["ID"]); What I would like is help from someone to modify this code so that I can insert 2 or more Field Values in the same operation. So as well as inserting the Value "ID" into the Child Table I can also insert the Value "client". Many thanks for reading. Carl.
  8. I am using jui datepicker. I have a table which has columns StartYear and EndYear set to varchar data type. I need to store the Start Year in the format of Month Year for example Start Year : Jan 2023 End Year : Jan 2024 I have configured the jui date picker to show only Month and Year. Data is getting correctly saved in the table in create action, but on the update form the same data is not fetched correctly as shown in below image Below is the code _form.php <?php use yii\helpers\Html; use yii\bootstrap\ActiveForm; use yii\jui\DatePicker; use yii\helpers\ArrayHelper; ?> <style type="text/css"> .ui-datepicker-calendar { display: none; } </style> <script> $(document).ready(function() { $('.picker').datepicker({ changeMonth: true, changeYear: true, dateFormat: 'MM yy', onClose: function() { var iMonth = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var iYear = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); $(this).datepicker('setDate', new Date(iYear, iMonth, 1)); }, }); }); </script> <?php $form = ActiveForm::begin();?> <?= $form->field($model, 'StartYear')->widget(DatePicker::classname(), [ //'language' => 'ru', 'options' => ['class' => 'form-control picker','readOnly'=>'readOnly'], 'clientOptions'=>['changeMonth'=>true, 'changeYear'=>true, 'dateFormat' => 'MM yy', 'readOnly'=>true] ]) ?> <?= $form->field($model, 'EndYear')->widget(DatePicker::classname(), [ //'language' => 'ru', 'options' => ['class' => 'form-control picker','readOnly'=>'readOnly'], 'clientOptions'=>['changeMonth'=>true, 'changeYear'=>true, 'dateFormat' => 'MM yy', 'readOnly'=>true] ]) ?> <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> <?php ActiveForm::end(); ?>
  9. I am creating a real estate management system and I have run into this problem and I have run out of ideas of how to get this things render the info of the house as I intend it to. This page is rendered by listings.js the code of this page is below This is the page where when i click on a house it shoud take me to the next page and renders its info from the database accroding to its corresponding id But I am not getting the info of the house on the next page this is what I am getting on the console I am writing the frontend in reactjs This is listings.js import React, { useState, useEffect } from 'react'; import axios from 'axios'; import { Link } from 'react-router-dom'; import './css/Listings.css'; const Listings = () => { const [houses, setHouses] = useState([]); const [currentPage, setCurrentPage] = useState(1); const [searchTerm, setSearchTerm] = useState(''); // State for search term useEffect(() => { const fetchHouses = async () => { try { const response = await axios.get('http://localhost/api/listings.php'); setHouses(response.data); } catch (error) { console.error('Error fetching houses:', error); } }; fetchHouses(); }, []); const handleNextPage = () => { setCurrentPage(currentPage + 1); }; const handlePrevPage = () => { setCurrentPage(currentPage - 1); }; const startIndex = (currentPage - 1) * 6; const endIndex = startIndex + 6; const handleHouseClick = (id) => { console.log(`House ID: ${id}`); axios .post(`http://localhost:80/api/houseinfo.php?id=${id}`) .then((response) => { console.log('Response:', response.data); }) .catch((error) => { console.error('Error:', error); }); }; const handleSearchTermChange = (event) => { setSearchTerm(event.target.value); }; // Function to handle form submission const handleSubmit = (event) => { event.preventDefault(); console.log('Search Term:', searchTerm); }; return ( <div className="listings-container"> <form className="search-form" onSubmit={handleSubmit}> <input type="text" className="search-input" placeholder="Search by title, location, or type" value={searchTerm} onChange={handleSearchTermChange} /> <button type="submit" className="search-button"> Search </button> </form> <div className="house-grid"> {houses .filter( (house) => house.title.toLowerCase().includes(searchTerm.toLowerCase()) || house.location.toLowerCase().includes(searchTerm.toLowerCase()) || house.type.toLowerCase().includes(searchTerm.toLowerCase()) ) .slice(startIndex, endIndex) .map((house, index) => ( <div key={index} className="house-card"> <Link to={`/houseinfo/${house.id}`} className="house-card-content" onClick={() => handleHouseClick(house.id)} // Pass house id to handleHouseClick > <img src={house.image1} alt={house.title} className="house-image" /> <h2 className="house-title">{house.title}</h2> </Link> </div> ))} </div> <div className="pagination"> {currentPage > 1 && ( <button className="pagination-button" onClick={handlePrevPage}> {'<'} </button> )} <span className="pagination-page">{currentPage}</span> {endIndex < houses.length && ( <button className="pagination-button" onClick={handleNextPage}> {'>'} </button> )} </div> </div> ); }; export default Listings; This is the houseinfo.js import React, { useState, useEffect } from 'react'; import { useParams } from 'react-router' const HouseInfo = ({ match }) => { const [listings, setListings] = useState(null); const {id} = useParams(); useEffect(() => { // Fetch house data from API based on house ID const fetchListings = async () => { try { const response = await fetch(`http://localhost:80/api/houseinfo/${id}`); const data = await response.json(); setListings(data); } catch (error) { console.error('Error fetching house:', error); } }; fetchListings(); }, [id]); if (!listings) { return <div>Loading...</div>; } return ( <div> <h1>House Information</h1> <ul> <li>Title: {listings.title}</li> <li>Location: {listings.location}</li> <li>Price: {listings.price}</li> </ul> </div> ); }; export default HouseInfo; And I am writing backend in php This is houseinfo.php <?php header('Content-Type: application/json'); header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: GET'); header('Access-Control-Allow-Headers: Content-Type'); $conn = mysqli_connect('localhost', 'root', '', 'realestate1'); if (!$conn) { die('Failed to connect to MySQL: ' . mysqli_connect_error()); } $houseId = $_GET['id']; $query = "SELECT * FROM listings WHERE id = ?"; $stmt = mysqli_prepare($conn, $query); mysqli_stmt_bind_param($stmt, 'i', $houseId); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); if (!$result) { die('Failed to fetch house data: ' . mysqli_error($conn)); } if (mysqli_num_rows($result) == 0) { die('House not found'); } $house = mysqli_fetch_assoc($result); $houseJson = json_encode($house); echo $houseJson; mysqli_stmt_close($stmt); mysqli_close($conn); ?> I am getting this on the backend api
  10. Fatal error: Uncaught PHPMailer\PHPMailer\Exception: SMTP Error: Could not authenticate. in C:\xampp\htdocs\myproject\vendor\phpmailer\phpmailer\src\PHPMailer.php:2213 Stack trace: #0 C:\xampp\htdocs\myproject\vendor\phpmailer\phpmailer\src\PHPMailer.php(2020): PHPMailer\PHPMailer\PHPMailer->smtpConnect(Array) #1 C:\xampp\htdocs\myproject\vendor\phpmailer\phpmailer\src\PHPMailer.php(1679): PHPMailer\PHPMailer\PHPMailer->smtpSend('Date: Sun, 30 A...', '\r\n <h2>You h...') #2 C:\xampp\htdocs\myproject\vendor\phpmailer\phpmailer\src\PHPMailer.php(1517): PHPMailer\PHPMailer\PHPMailer->postSend() #3 C:\xampp\htdocs\myproject\code.php(44): PHPMailer\PHPMailer\PHPMailer->send() #4 C:\xampp\htdocs\myproject\code.php(57): sendemail_verify('Harivote User', 'harivoteuser@gm...', 'HariVoteuser0') #5 {main} thrown in C:\xampp\htdocs\myproject\vendor\phpmailer\phpmailer\src\PHPMailer.php on line 2213 <?php session_start(); include "dbcon.php"; //Import PHPMailer classes into the global namespace use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; use PHPMailer\PHPMailer\Exception; //Load Composer's autoloader require 'vendor/autoload.php'; /** * Summary of sendemail_verify * @param mixed $name * @param mixed $email * @param mixed $verify_token * @return void */ function sendemail_verify($name,$email,$verify_token) { $mail = new PHPMailer(true); $mail->isSMTP(); //Send using SMTP $mail->Host = 'smtp.gmail.com'; //Set the SMTP server to send through $mail->SMTPAuth = true; //Enable SMTP authentication $mail->Username = 'harivoteuser@gmail.com'; //SMTP username $mail->Password = 'Sec_ret123'; //SMTP password $mail->SMTPSecure = "PHPMailer::ENCRYPTION_STARTTLS"; //Enable implicit TLS encryption $mail->Port = 587; //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS` $mail->setFrom("harivoteuser@gmail.com", $name); $mail->addAddress($email); //Add a recipient $mail->isHTML(true); //Set email format to HTML $mail->Subject = 'Email Verification from HariVote'; $email_template = " <h2>You have Registered with Harivote</h2> <h5>Verify your email address to Login with the below given link </h5> <br/><br/> <a href='http://http://localhost/myproject/verify-email.php?token=$verify_token'>Click Me </a> "; $mail->Body = $email_template; $mail->send(); //echo 'Message has been sent'; } if(isset($_POST['register_btn'])) { $name = $_POST['name']; $phone = $_POST['phone']; $email = $_POST['email']; $password = md5(rand()); $verify_token = $_POST['password']; sendemail_verify("$name","$email","$verify_token"); echo 'send or not?'; //Email exists or not $check_email_query = "SELECT email FROM users WHERE email='$email'LIMIT 1"; $check_email_query_run = mysqli_query($con, $check_email_query); if(mysqli_num_rows($check_email_query_run)>0) { $_SESSION['status'] = "Email Id already Exists"; header("Location: register.php"); } else { // Inswer User / Registered User Data $query = "INSERT INTO users (name,phone,email,password,verify_token) VALUES ('$name','$phone','$email','$password','$verify_token',)"; $query_run = mysqli_query($con,$query); if($query_run) { sendemail_verify("$name","$email","$verify_token"); $_SESSION['status'] = "Registration Successful.! Please verify your Email Address."; header("Location: register.php"); } else { $_SESSION['status'] = "Registration Failed"; header("Location: register.php"); } } } ?>
  11. I am using a web video script that has Paypal integrated. Upon attempting a live transaction to test, the process proceeds to Paypal, shows the transaction amount and returns to the web site successfully, however, no amount is added to the website and no amount is deducted from the paypal user account. I see no errors at paypal or on the website. After communicating with Paypal Merchant Support they said: "You do need to work with your developer and request them to find out why the capture request would not be invoked after the order is created and approved and fix it accordingly". However, the developer is unavailable, so I am attempting to find/fix the issue. Can you tell me if you see anything that might cause an issue with the code below? Or any clues I might look into? I look forward to any suggestions. <?php if (IS_LOGGED == false && $first != 'success_fortumo' && $first != 'success_aamarpay' && $first != 'cashfree_paid' && $first != 'iyzipay_paid' && $first != 'success_yoomoney') { $data = array( 'status' => 400, 'error' => 'Not logged in' ); echo json_encode($data); exit(); } require 'assets/includes/paypal_config.php'; $payment_currency = $pt->config->payment_currency; $paypal_currency = $pt->config->paypal_currency; if ($first == 'replenish') { $data = array('status' => 400); $request = (!empty($_POST['amount']) && is_numeric($_POST['amount'])); if ($request === true) { $price = PT_Secure($_POST['amount']); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url . '/v2/checkout/orders'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, '{ "intent": "CAPTURE", "purchase_units": [ { "items": [ { "name": "Wallet Replenishment", "description": "Pay For ' . $pt->config->name.'", "quantity": "1", "unit_amount": { "currency_code": "'.$pt->config->paypal_currency.'", "value": "'.$price.'" } } ], "amount": { "currency_code": "'.$pt->config->paypal_currency.'", "value": "'.$price.'", "breakdown": { "item_total": { "currency_code": "'.$pt->config->paypal_currency.'", "value": "'.$price.'" } } } } ], "application_context":{ "shipping_preference":"NO_SHIPPING", "return_url": "'.PT_Link("aj/wallet/get_paid?status=success&amount=").$price.'", "cancel_url": "'.PT_Link("aj/wallet/get_paid?status=false").'" } }'); $headers = array(); $headers[] = 'Content-Type: application/json'; $headers[] = 'Authorization: Bearer '.$pt->paypal_access_token; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $result = curl_exec($ch); if (curl_errno($ch)) { echo 'Error:' . curl_error($ch); } curl_close($ch); $result = json_decode($result); if (!empty($result) && !empty($result->links) && !empty($result->links[1]) && !empty($result->links[1]->href)) { $data = array( 'status' => 200, 'type' => 'SUCCESS', 'url' => $result->links[1]->href ); } elseif(!empty($result->message)){ $data = array( 'type' => 'ERROR', 'details' => $result->message ); } echo json_encode($data); exit(); } } if ($first == 'get_paid') { $data['status'] = 500; if (!empty($_GET['amount']) && is_numeric($_GET['amount']) && !empty($_GET['token'])) { $amount = (int)PT_Secure($_GET['amount']); $token = PT_Secure($_GET['token']); include_once('assets/includes/paypal.php'); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url . '/v2/checkout/orders/'.$token.'/capture'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); $headers = array(); $headers[] = 'Content-Type: application/json'; $headers[] = 'Authorization: Bearer '.$pt->paypal_access_token; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $result = curl_exec($ch); if (curl_errno($ch)) { header("Location: " . PT_Link('wallet')); exit(); } curl_close($ch); if (!empty($result)) { $result = json_decode($result); if (!empty($result->status) && $result->status == 'COMPLETED') { $update = array('wallet' => ($user->wallet_or += $amount)); $db->where('id',$user->id)->update(T_USERS,$update); $payment_data = array( 'user_id' => $user->id, 'paid_id' => $user->id, 'admin_com' => 0, 'currency' => $pt->config->paypal_currency, 'time' => time(), 'amount' => $amount, 'type' => 'ad' ); $db->insert(T_VIDEOS_TRSNS,$payment_data); $_SESSION['upgraded'] = true; $url = PT_Link('wallet'); if (!empty($_COOKIE['redirect_page'])) { $redirect_page = preg_replace('/on[^<>=]+=[^<>]*/m', '', $_COOKIE['redirect_page']); $url = preg_replace('/\((.*?)\)/m', '', $redirect_page); } header("Location: $url"); exit(); } } } header("Location: " . PT_Link('wallet')); exit(); } ...
  12. Hi there. I have posts, post comments and users tables which are all fine in and of themselves, but I'd like users to have a unique name that's specific only to the post to hide their real username. This applies to the post itself, and the comments of the post and must remain consistent. For example, if Bill made a post with the name "BigFish", if they comment on their own post then their comments will also have that same name. Likewise, if another user comments with the name "BowlingBall", their subsequent comments will also have the same name. Now, my first attempt was to have an intermediate table of sorts, containing the post_id, user_id and display_name. This takes the appearance of a composite primary key, which are not supported in Laravel. Laravel relationships of such nature can be achieved with a package called Compoships, which does work and given the nature of the table, their resulting query being a gigantic mess of the following is reasonable at best. (post_id == ? AND user_id == ?) OR (post_id == ? AND user_id == ?) OR ... However, that can quickly scale and definitely hurts. Another way to tackle it is to retrieve all display names for each post ID, but that's then retrieving unnecessary data. It's also possible to scrap the table, store the names in the posts and post_comments tables. That's as simple as checking if the commenter is the post author and use that name, or checking if they've previously commented and use that name. I'm not sure if that's ideal either. This brings me back here, after a decade of inactivity, and I do apologise for the lengthy post. How would I go about achieving what I want to do in the best way possible? What would you do in this scenario? Thanks in advance, looking forward to y'all suggestions.
  13. Hi, I running a query that groups merge.Description where the StoreId is the same, and replacing the comma with a line break. The problem I'm getting is the string only returns 1023 character's and I need it to return more? Any help would be great Cheers $rows = mysql_query("SELECT REPLACE(GROUP_CONCAT(merge.Description), ',', CHAR(13)) FROM merge GROUP BY merge.StoreId");
  14. I get this message and not sure how to fix it...... Success... NULL Warning: mysqli_get_host_info() expects parameter 1 to be mysqli, null given in /www/zzl.org/o/t/t/ottawaglandorfems/htdocs/class-db.php on line 14 Success... NULL This is my form - <?php require_once('class-db.php'); /** * function to check the validity of the given string * $what = what you are checking (phone, email, etc) * $data = the string you want to check */ function isValid( $what, $data ) { switch( $what ) { // validate a phone number case 'phone': $pattern = "/^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/i"; break; // validate email address case 'email': $pattern = "/^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$/i"; break; default: return false; break; } return preg_match($pattern, $data) ? true : false; } $errors = array(); if( isset($_POST['btn_submit']) ) { if( !isValid( 'phone', $_POST['phone'] ) ) { $errors[] = 'Please enter a valid phone number'; } if( !isValid( 'email', $_POST['email'] ) ) { $errors[] = 'Please enter a valid email address'; } } if( !empty($errors) ) { foreach( $errors as $e ) echo "$e <br />"; } if ( !empty ( $_POST ) ) { $type = 'post'; $insert = insert($type, $values); } ?> <html> <head> <title>Registration form for Octoberfest With O-G EMS 2013</title> </head> <body> <form action="" method="post"> <p Registration /> <p>First Name:<input type="text" name="fname" > </p> <p>Last Name:<input type="text" name="lname" > </p> <p>Phone Number:<input type="text" name="phone" ></p> <p>Address:<input type="text" name="address" ></p> <p>Department:<input type="text" name="department" ></p> <p>Email Address:<input type="text" name="email" ></p> <p>Level of Training:<input type="text" name="level" ></p> <input type="submit" name="btn_submit" value="Register"> </form> </body> </html> and this is my script <?php require_once('config1.php'); function connect() { $sql = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); if ($sql->connect_error) { die('Connect Error (' . $sql->connect_errno . ') ' . $sql->connect_error); }echo 'Success... ' . mysqli_get_host_info($link) . "\n"; return $sql; } function insert($type){ $sql=connect(); /* Set our params */ $fname = $_POST["fname"]; $lname = $_POST["lname"]; $phone = $_POST["phone"]; $address = $_POST["address"]; $department = $_POST["department"]; $email = $_POST["email"]; $level = $_POST["level"]; $query=("INSERT INTO Oktoberfest2013 (First_Name, Last_Name, Phone, Address, Department, Email_Address, Level_of_Traning) values (?, ?, ?, ?, ?, ?, ?)"); /* Create the prepared statement */ if ($stmt = $sql->prepare($query)); var_dump($qSelect); if ( !$sql->query($query) ) { return "Errormessage: $mysqli->error"; /* Bind our params */ $stmt->bind_param('sssssss', $fname, $lname, $phone, $address, $department, $email, $level); /* Execute the prepared Statement */ $stmt->execute(); } } function select($query) { $sql = connect(); $result = $sql->query($query); while ( $obj = $result->fetch_object() ) { $return[] = $obj; } } ?> Thanks in advance for the help.
  15. Hey guys, i was trying to add google recaptcha to my login register system, for a spam defense and just to give it a more professional feel. i already have my own conditional in my own system to make sure an email is not already used or to make sure a password is a certain length, etc.... i now want to add the existing code from google and add an additional conditional to make it flow as one. my issue so i followed the directions from goodle developers and when implementing the code by itself on a test page, i encounter no problems. i get the proper pass and fail, depending on what security code is entered. when i move that same logic into my already created system i then get a consistent failure with no pass. i am utterly confused as to why this is happening, if you guys can give me any suggestions that would be great. my code TEST PAGE .. WORKS FINE <?php include('include/init.php'); include('include/header.php'); require_once 'recaptchalib.php'; $privatekey = "6Lf5AeASAAAAAO5DJ1GcIAiwd8kkNbVBgrDrandom"; $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if (!$resp->is_valid) { echo 'FAILURE'; } else { echo 'SUCCESS'; // Your code here to handle a successful verification } ?> <tr> <form method='post' action='test.php' id='test'> <td class="register_td_left2"><span class="">Security Code:</span></td> <td valign="middle" style="padding-left:2px"> <?php require_once 'recaptchalib.php'; $publickey = "6Lf5AeASAAAAAPue6LLdUDttmPDc-NbRHcnrandom"; // you got this from the signup page echo recaptcha_get_html($publickey); ?></td> <input type='submit' value='Submit'></input> </form> </tr> Register page i try to implement the same logic require_once 'recaptchalib.php'; $privatekey = "6Lf5AeASAAAAAO5DJ1GcIAiwd8kkNbVBgrandom"; $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if (empty($_POST) === false) { $required_fields = array('register_email','register_username','password','confirm_pass','gender','month','date','year','country'); foreach($_POST as $key => $value){ if (empty($value) && in_array($key, $required_fields) === true) { $errors[] = '* All fields are required!'; break 1; } } if (empty($errors) === true) { if (user_exists($_POST['register_username']) === true) { $errors[] = 'Sorry, the username \'' . $_POST['register_username'] . '\' has already been taken. Please choose another username.'; } if (preg_match("/\\s/", $_POST['register_username']) == true) { $errors[] = 'Sorry your username must not contain any spaces!'; } if (strlen($_POST['password']) < 6 ){ $errors[] = 'Your Password must be a minimal 6 characters long'; } if ($_POST['password'] !== $_POST['confirm_pass']) { $errors[] = 'Your Passwords do not match, please make sure both passwords are the same!'; } if (filter_var($_POST['register_email'], FILTER_VALIDATE_EMAIL) === false) { $errors[] = 'A valid email adress is required'; } if(email_exists($_POST['register_email']) === true){ $errors[] = 'The email you provided is already in use. If you are having trouble remembering your user info click <a href="#">here</a>'; } if (!$resp->is_valid) { $errors[] = 'You need to enter a valid security code'; } } } <form name="register" action="register.php" method="post"> <tr> <td class="register_td_left2"><span class="">Security Code:</span></td> <td valign="middle" style="padding-left:2px"> <?php require_once 'recaptchalib.php'; $publickey = "6Lf5AeASAAAAAPue6LLdUDttmPDc-NbRandom"; // you got this from the signup page echo recaptcha_get_html($publickey); ?></td> </tr> </form> i left out most of the form , just to save some reading time for you guys. figure its of no importance. again i am puzzled as to why this doesnt work for me on this page, yet on the test page it works fine. please i have been stuck on this for far to long for such a simple thing. thanks.
  16. Hey guys, im trying to create a 'captcha' image for registration security for my site. currently i have 2 separate pages working together, my captcha.php file & my register.php now, what i am doing is trying to get a generate code that will be random and create an image with this string. this image will then be linked in the registration form where the user will have to match that random string image. sounds simple except , for some reason the code i have supplied from the tutorial is not outputting the image in the form. i have GD's installed on my server, and i have the font file saved also in the directory/ my code is : captcha.php <?session_start(); header('Content-type: image/jpeg'); $text = $_SESSION['secure']; $font_size = 30; $image_height = 200; $image_width = 40; $image = imagecreate($image_width, $image_height); imagecolorallocate($image, 255, 255, 255); // white $text_color = imagecolorallocate($image, 0, 0, 0); //black imagettftext($image, $font_size, 0, 15, 30, $text_color, 'font.ttf', $text); imagejpeg($image); ?> so in this i have created the image captcha.php should now be a jpeg.. i then go to my register.php declare the $_SESSION and input the src="captcha.php'' register.php <?php include('include/init.php'); $_SESSION['secure'] = rand(1000,9999); ?> and the form : <tr> <td class="register_td_left2"><span class="">Security Code:</span></td> <td valign="middle" style="padding-left:2px"><input id="security_code" name="security_code" type="text" maxlength="4" size="5"></td> <td align="left" valign="middle"><img src="generate.php" alt="Your Security Code"></td> </tr> this is my first time adding a captcha and going through this process. the only thing i can think that would not be allowing it output the image, would be the 'font.tff' not properly working, or for some odd reason i dont have the GD functions installed correctly. any suggestions ? or ideas ?
  17. I am attempting to create a php AJAX contact form , however the email never seems to arrive in my outlook. /* Jquery Validation using jqBootstrapValidation example is taken from jqBootstrapValidation docs */ $(function() { $("input,textarea").jqBootstrapValidation( { preventSubmit: true, submitError: function($form, event, errors) { // something to have when submit produces an error ? // Not decided if I need it yet }, submitSuccess: function($form, event) { event.preventDefault(); // prevent default submit behaviour // get values from FORM var name = $("input#name").val(); var email = $("input#email").val(); var phone = $("input#phone").val(); var message = $("textarea#message").val(); var firstName = name; // For Success/Failure Message // Check for white space in name for Success/Fail message if (firstName.indexOf(' ') >= 0) { firstName = name.split(' ').slice(0, -1).join(' '); } $.ajax({ url: "./bin/contact_me.php", type: "POST", data: {name: name,phone:phone, email: email, message: message}, cache: false, success: function() { // Success message $('#success').html("<div class='alert alert-success'>"); $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×") .append( "</button>"); $('#success > .alert-success') .append("<strong>Your message has been sent. </strong>"); $('#success > .alert-success') .append('</div>'); //clear all fields $('#contactForm').trigger("reset"); }, error: function() { // Fail message $('#success').html("<div class='alert alert-danger'>"); $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×") .append( "</button>"); $('#success > .alert-danger').append("<strong>Sorry "+firstName+" it seems that my mail server is not responding...</strong> Could you please email me directly ? Sorry for the inconvenience!"); $('#success > .alert-danger').append('</div>'); //clear all fields $('#contactForm').trigger("reset"); }, }) }, filter: function() { return $(this).is(":visible"); }, }); $("a[data-toggle=\"tab\"]").click(function(e) { e.preventDefault(); $(this).tab("show"); }); }); /*When clicking on Full hide fail/success boxes */ $('#name').focus(function() { $('#success').html(''); }); <?php require("../lib/phpmailer/PHPMailerAutoload.php"); if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['phone']) || empty($_POST['message']) || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) { echo "No arguments Provided!"; return false; } $m = new PHPMailer(); $m->IsSMTP(); $m->SMTPAuth = true; $m->SMTPDebug = 2; $m->Host = "smtp-mail.outlook.com"; $m->Username = ""; $m->Password = ""; $m->SMTPSecure = 'tls'; $m->Port = 587; $m->addAddress('EXAMPLE@outlook.com', $name); $name = $_POST['name']; $email_address = $_POST['email']; $phone = $_POST['phone']; $message = $_POST['message']; $m->Subject = "Contact Form has been submitted"; $m->Body = "You have received a new message. <br><br>". " Here are the details:<br> Name: $name <br> Phone Number: $phone <br>". "Email: $email_address<br> Message <br> $message"; if(!$m->Send()) { echo "Mailer Error: " . $m->ErrorInfo; exit; } ?>
  18. Hi I am trying to send email through following php code to may gmail account but it givrs me SMTP Error: Could not connect to SMTP host. ******************************************************************************************************************************************************* <?phpif(isset($_POST['submit'])){ $message='Full Name: '.$_POST['fullname'].'<br />Subject: '.$_POST['subject'].'<br />Phone: '.$_POST['phone'].'<br />Email: '.$_POST['emailid'].'<br />Comments: '.$_POST['comments'].''; require "phpmailer/class.phpmailer.php"; //include phpmailer class // Instantiate Class $mail = new PHPMailer(); // Set up SMTP $mail->IsSMTP(); // Sets up a SMTP connection $mail->SMTPAuth = true; // Connection with the SMTP does require authorization $mail->SMTPSecure = "ssl"; // Connect using a TLS connection $mail->Host = "smtp.gmail.com"; //Gmail SMTP server address $mail->Port = 465; //Gmail SMTP port $mail->Encoding = '7bit'; // Authentication $mail->Username = "myemail@gmail.com"; // Your full Gmail address $mail->Password = "mypassword"; // Your Gmail password // Compose $mail->SetFrom($_POST['emailid'], $_POST['fullname']); $mail->AddReplyTo($_POST['emailid'], $_POST['fullname']); $mail->Subject = "New Contact Form Enquiry"; // Subject (which isn't required) $mail->MsgHTML($message); // Send To $mail->AddAddress("myemail@gmail.com", "Recipient Name"); // Where to send it - Recipient $result = $mail->Send(); // Send! $message = $result ? 'Successfully Sent!' : 'Sending Failed!'; unset($mail); }?><html><head> <title>Contact Form</title></head><body> <div style="margin: 100px auto 0;width: 300px;"> <h3>Contact Form</h3> <form name="form1" id="form1" action="" method="post"> <fieldset> <input type="text" name="fullname" placeholder="Full Name" /> <br /> <input type="text" name="subject" placeholder="Subject" /> <br /> <input type="text" name="phone" placeholder="Phone" /> <br /> <input type="text" name="emailid" placeholder="Email" /> <br /> <textarea rows="4" cols="20" name="comments" placeholder="Comments"></textarea> <br /> <input type="submit" name="submit" value="Send" /> </fieldset> </form> <p><?php if(!empty($message)) echo $message; ?></p> </div> </body></html>
  19. Hi friends, i have a problem. i try to make pagination. I didn't added numbers and the number stayed next to the images. Numbers is no display and it is next the images. And i don't want to give "padding-left" for first image but when i use "padding-left" for images, it is giving all of them. <?php $sayfa = intval($_GET["sayfa"]); if(!$sayfa) {$sayfa = 1;} $say = $db->query("SELECT * FROM resimlerekle"); $toplamveri = $say->rowCount(); // Verileri Saydırdık $limit = 8; $sayfa_sayisi = ceil($toplamveri/$limit); if($sayfa > $sayfa_sayisi) { $sayfa = 1; } $goster = $sayfa * $limit - $limit; $gorunensayfa = 6; $resimcek = $db->query("SELECT * FROM resimlerekle ORDER BY cokluresimekle_id DESC LIMIT $goster,$limit"); $resimlerial = $resimcek->fetchAll(PDO::FETCH_ASSOC); ?> <?php foreach ($resimlerial as $resim) { ?> <div style="float: left; padding-left: 10px;"> <div><img <?php echo $resim; ?> style="max-width:250px;" src="../../../upload/cokluresim/<?php echo $resim["cokluresimekle_resim"]; ?>" ></div> <div style="max-width:250px; max-height:50px; background-color:#d6d4d4; line-height:50px; text-align:center;"><?php echo $resim['cokluresimekle_baslik']; ?></div> </div> <?php } ?> <!-- Benim Eklediğim Kodlar Bitiş --> <?php if ($sayfa > 1) { ?> <span><a href="index.php?sayfa=1">İlk</a></span> <div><a href="index.php?sayfa=<?php echo $sayfa - 1 ?>">Önceki</a></div> <?php } ?> <?php for($i = $sayfa - $gorunensayfa; $i < $sayfa + $gorunensayfa +1; $i++) { if($i > 0 and $i <= $sayfa_sayisi) { if($i == $sayfa) { echo '<span>'.$i.'</span>'; }else{ echo '<a href="index.php?sayfa='.$i.'">'.$i.'</a>'; } } } ?> <?php if ($sayfa != $sayfa_sayisi) { ?> <div><a href="index.php?sayfa=<?php echo $sayfa + 1 ?>">Sonraki</a></div> <div><a href="index.php?sayfa<?php echo $sayfa_sayisi ?>">Son</a></div> <?php } ?>
  20. We can create .php files every time I click on it will check to Simple "E: /e.txt" and read inside it and create / wirte to print .php file hosting We can create .php files every time I click on it will check to Simple "E: /e.txt" and read inside it and create / wirte to print .php file hosting?? , please help
  21. Hi there, I am new to the forum was really unsure where to post my thread since I have no idea where the issue in my application is actually coming from. I've put a flash game on facebook as a canvas app. Once a user authorizes my application I grab their name and id and then use the id to check if they already exist in my database. If they do I pull their score otherwise I add them into the db. Every browser and 3 different machines I have tried it on, and with multiple user accounts, it always works. I have never been able to reproduce the issue of the user not getting registered in the db, but facebook shows that about 28 people have authorized my app, but only 13 of them have been registered in the db. Some friends I asked to try the game told me they liked the game, and facebook says they played it, but they do not show up in my apps database. 13 out of 28 captured! It makes me wanna cry cause all those uncaptured users are not getting the proper experience. I'm using Amfphp framework to bridge flash and php. The app is hosted for free on Heroku and uses the free pgsql db they provide. The app can be seen here: http://apps.facebook...wordfighterbeta After the flash loads I call the AS3 API for facebook: import com.facebook.graph.Facebook; Facebook.init(APP_ID, onInit); //my app id is correctly set function onInit(result:Object, fail:Object):void { if (result) { Facebook.api("/me", getUserInfoHandler, null, "GET"); loggedIn = true; } else { resultTxt.text = "In order to save your highscores this app requires facebook authentication."; loginBtn.label = 'Facebook Login'; loginBtn.addEventListener(MouseEvent.CLICK, handleLoginClick, false, 0, true); loginBtn.enabled = true; } } //called when they click 'login' function handleLoginClick(event:MouseEvent):void { Facebook.login(onLogin); } function onLogin(result:Object, fail:Object):void { if (result) { Facebook.api("/me", getUserInfoHandler, null, "GET"); } else { resultTxt.text = "Authorization denied."; } } function getUserInfoHandler(result:Object, fail:Object):void { if (result) { userName = result.name; userID = result.id; registerUser(userID, userName); //this is where I try to add the user to the database } else { resultTxt.text = 'fail'; } } function registerUser(id, user):void { if (! local) { _netConnection = new NetConnection(); _netConnection.connect("https://sheltered-plateau-6639.herokuapp.com/Amfphp/"); _netConnection.call("WordFighter/registerUser", new Responder(handleResultArray, null), id,user); } } function handleResultArray(result:*):void { for each (var user:Object in result) { userScore = user.score; //start the game } And here is the registerUser function I wrote in PHP: public function registerUser($id, $name){ $host = "ec2-107-22-161-45.compute-1.amazonaws.com"; $user = "jytgyzybpoqjed"; $pass = "password"; $db = "dbvgstj2v06pit"; $con = pg_connect("host=$host dbname=$db user=$user password=$pass") or die ("Could not connect to server\n"); $query = "SELECT * FROM noobs WHERE fbID='$id'"; $rs = pg_query($con, $query) or die("Cannot execute query: $query\n"); if(pg_num_rows($rs) > 0){ $noobs = array(); $noobs[] = pg_fetch_assoc($rs); return $noobs; } else { $query = "INSERT INTO noobs (fbID, name, score) VALUES ('$id', '$name', '0')"; $rs = pg_query($query) or die("Cannot execute query: $query\n"); $query = "SELECT * FROM noobs WHERE fbID='$id'"; $rs = pg_query($query) or die("Cannot execute query: $query\n"); $noobs = array(); $noobs[] = pg_fetch_assoc($rs); return $noobs; } pg_close($con); } So yea. Who is the genius out there that can tell me why so many users aren't getting saved. The part that really confuses me is that when I look at the actionscript I see no way they can advance and play the game without the php returning an answer to the registerUser call since that's the only place in the code that starts the game, so why are some people playing the game and evading the database?
  22. I've finally got the time to learn web sockets and have choosen to use: http://socketo.me/docs/push to do so. It all works perfectly fine without SSL. The moment it's enabled the client javascript will not connect and will output "WebSocket opening handshake timed out". I've tried the server with and without the TLS options. client.html, post.php, server.php <script type="text/javascript" src="autobahn.js"></script> <script> var conn = new ab.Session('wss://domain.com:8443', function() { console.log('Connected'); conn.subscribe('kittensCategory', function(topic, data) { // This is where you would add the new article to the DOM (beyond the scope of this tutorial) console.log('New article published to category "' + topic + '" : ' + data.title); }); }, function() { console.warn('WebSocket connection closed'); }, {'skipSubprotocolCheck': true} ); </script> <?php require dirname(__DIR__) . '/socket/vendor/autoload.php'; // post.php ??? // This all was here before ;) $entryData = array( 'category' => 'kittensCategory' , 'title' => 'My Impressive Title' , 'article' => 'Just me the best, nothing new!' , 'when' => time() ); // This is our new stuff $context = new ZMQContext(); $socket = $context->getSocket(ZMQ::SOCKET_PUSH, 'my pusher'); $socket->connect("tcp://localhost:5555"); $socket->send(json_encode($entryData)); echo 'All Sent!'; <?php require dirname(__DIR__) . '/socket/vendor/autoload.php'; use Ratchet\ConnectionInterface; use Ratchet\Wamp\WampServerInterface; class Pusher implements WampServerInterface { /** * A lookup of all the topics clients have subscribed to */ protected $subscribedTopics = array(); public function onSubscribe(ConnectionInterface $conn, $topic) { echo 'Subbed'; $this->subscribedTopics[$topic->getId()] = $topic; } /** * @param string JSON'ified string we'll receive from ZeroMQ */ public function onBlogEntry($entry) { echo 'Hello!'; $entryData = json_decode($entry, true); // If the lookup topic object isn't set there is no one to publish to if (!array_key_exists($entryData['category'], $this->subscribedTopics)) { return; } $topic = $this->subscribedTopics[$entryData['category']]; // re-send the data to all the clients subscribed to that category $topic->broadcast($entryData); } /* The rest of our methods were as they were, omitted from docs to save space */ //public function onSubscribe(ConnectionInterface $conn, $topic) { // } public function onUnSubscribe(ConnectionInterface $conn, $topic) { } public function onOpen(ConnectionInterface $conn) { } public function onClose(ConnectionInterface $conn) { } public function onCall(ConnectionInterface $conn, $id, $topic, array $params) { // In this application if clients send data it's because the user hacked around in console $conn->callError($id, $topic, 'You are not allowed to make calls')->close(); } public function onPublish(ConnectionInterface $conn, $topic, $event, array $exclude, array $eligible) { // In this application if clients send data it's because the user hacked around in console $conn->close(); } public function onError(ConnectionInterface $conn, \Exception $e) { } } $loop = React\EventLoop\Factory::create(); $pusher = new Pusher; // Listen for the web server to make a ZeroMQ push after an ajax request $context = new React\ZMQ\Context($loop); $pull = $context->getSocket(ZMQ::SOCKET_PULL); $pull->bind('tcp://127.0.0.1:5555'); // Binding to 127.0.0.1 means the only client that can connect is itself $pull->on('message', array($pusher, 'onBlogEntry')); // Set up our WebSocket server for clients wanting real-time updates $webSock = new React\Socket\Server('0.0.0.0:8443', $loop, array( 'tls' => array( 'local_cert' => 'cert.pem', 'local_pk' => 'private.key', // path to your server private key, 'verify_peer' => FALSE ))); // Binding to 0.0.0.0 means remotes can connect $webServer = new Ratchet\Server\IoServer( new Ratchet\Http\HttpServer( new Ratchet\WebSocket\WsServer( new Ratchet\Wamp\WampServer( $pusher ) ) ), $webSock ); $loop->run();
  23. Hi All, I have a set of question to bring out. I will be need to setup a questionnaires page to let user to fill in. The questions is statics, so i don't think i will setup a module to let admin to setup questions/ update questions. So, the thing i need to focus is to create a questionnaires form to get all the inputs and store into the database. 1. Has your manager spoken to you with regards to your resignation? Yes/No Comment: _______________________________________________________________________________________ 2a. Have you considered other jobs in ABC Company before making this decision? Yes/No 2b. If No, is there any particular area of interest that you would like to consider? (HR can assist with job matches) ________________________________________________________________________________________________ 3. Which factors attracted you to join ABC Company? (check all that apply) A. Interesting Job C. Working environment B. Opportunities for training, advancement, career growth D. Pay & Benefits E. Other ________________________________ 4. What are your reasons for leaving ABC Company? (check all that apply) A. Change in career H. Job Nature, Work load or work hours I. Quality of supervision B. Family or personal needs J. Lack of recognition for work C. Moving from area K. Lack of advancement opportunities D. To further education E. Pay dissatisfaction F. Benefits dissatisfaction G. Work environment So if i create a html form and pass all the value to database, im not sure how to store the check box value, have a look to the attachment. is it not a good practice to store table in a row right? but how could i store a same form in a different row of data? how to store the check box value? i need to create an individual column for them? what is the value should i store when click all the value? this form will generate report in future, i still dun have the template currently, but it should be something like average how many people choose the answer. Need Help..~!
  24. For decades I have lain awake at night pondering this major conundrum. Why do PDO::FETCH_BOTH and mysqli->fetch_array() exist? Surely one either wants an associative array or, occasionally, a numerically indexed array? Further, given their uselessness, why the hell are they the default? Can anyone enlighten me as to their raison d'être?
  25. I am using osclass Osclass v8.0.2 free classified. I am trying to implement load more i.e infinite scroll facility on homepage page. When user scrolls, listings should be loaded automatically to give users pleasant and engaging experiences. Below is my code: Got from plugin. That I want to directly insert in osclass script. For the learning purpose. I am trying it on my localhost. Please help to achieve this, any help is highly appreciated. Thanks. <?php $content_block = htmlspecialchars_decode(inf_param('#main')); $listings_parent_block = htmlspecialchars_decode(inf_param('#listing-card-list')); $pagination_block = htmlspecialchars_decode(inf_param('.paginate')); $pagination_next = htmlspecialchars_decode(inf_param('a.searchPaginationNext')); $loaded_listings_count = htmlspecialchars_decode(inf_param('loaded_listings_count')); $report_errors = htmlspecialchars_decode(inf_param('report_errors')); ?> <style> <?php echo $pagination_block; ?> {display:none!important;} .inf-loader {display:none;width:100%;padding:25px 5px;margin:20px 0;background:#eee;border-radius:6px;color:#777;font-size:16px;text-align:center;line-height:20px;} .inf-loader > div {display:inline-block;width:auto;position:relative;padding-left:44px;} .inf-loader img {position:absolute;display:inline-block;top:-6px;left:0;width:32px;height:32px;max-height:32px;max-width:32px;} .inf-loader span {display:inline-block;font-weight:bold;line-height:20px;font-size:14px;} <?php echo $content_block; ?>.loading .inf-loader {display:inline-block;} </style> <script async type="text/javascript"> $(document).ready(function() { var currentPag = 1; var isLoading = false; var pagUrl = ''; var newUrl = ''; var oldUrl = ''; // ADD LOADING BLOCK ABOVE PAGINATION var loadingBlock = '<div class="inf-loader"><div><img src="<?php echo osc_base_url(); ?>oc-content/plugins/infinite/img/loader.gif"/><span><?php echo osc_esc_js(__('Loading items...', 'infinite')); ?></span></div></div>'; $(window).scroll(function(e) { var scroll = $(window).scrollTop(); var threshold = $('<?php echo $content_block; ?>').position().top + $('<?php echo $content_block; ?>').innerHeight() - 100; var position = $(window).scrollTop() + $(window).innerHeight(); if($('<?php echo $pagination_next; ?>').length) { pagUrl = $('<?php echo $pagination_next; ?>').attr('href'); } else { pagUrl = ''; } //console.log(oldUrl + '--->' + pagUrl ); // loading block add above pagination now if(!$('<?php echo $content_block; ?>').find('.inf-loader').length) { $(loadingBlock).insertBefore($('<?php echo $pagination_block; ?>')); } if(!$('<?php echo $content_block; ?>').length || !$('<?php echo $listings_parent_block; ?>').length || !$('<?php echo $pagination_block; ?>').length || !$('<?php echo $pagination_next; ?>').length) { infCheckBlocks(); } else if(position > threshold && isLoading == false && pagUrl != oldUrl && pagUrl != '' && pagUrl != '#') { isLoading = true; $('<?php echo $content_block; ?>').addClass('loading'); $.ajax({ url: pagUrl, type: "GET", success: function(response){ var length = response.length; var data = $(response).contents().find('<?php echo $listings_parent_block ; ?>').html(); var pagBlock = $(response).contents().find('<?php echo $pagination_block; ?>'); var currItemCount = $(response).contents().find('<?php echo $loaded_listings_count; ?>').text(); oldUrl = pagUrl; $('<?php echo $pagination_block; ?>').html(pagBlock); $('<?php echo $listings_parent_block; ?>').append(data); if($('<?php echo $loaded_listings_count; ?>').length) { $('<?php echo $loaded_listings_count; ?>').text(currItemCount); } // lazy load if exists if(typeof $.fn.Lazy !== 'undefined') { $('<?php echo $listings_parent_block; ?>').find('img.lazy').Lazy({ appendScroll: window, scrollDirection: 'both', effect: 'fadeIn', effectTime: 300, afterLoad: function(element) { setTimeout(function() { element.css('transition', '0.2s'); }, 300); } }); } isLoading = false; currentPag = currentPag + 1; $('<?php echo $content_block; ?>').removeClass('loading'); }, error: function(response){ hasPag = false; $('<?php echo $content_block; ?>').removeClass('loading'); response = response.responseText; console.log(response); console.log(data); } }); } }); }); function infCheckBlocks() { <?php if($report_errors == 1) { ?> console.log('<?php echo osc_esc_js(__('Infinite scroll failed to load next items, check message bellow!', 'infinite')); ?>'); if(!$('<?php echo $content_block; ?>').length) { console.log('<?php echo osc_esc_js(sprintf(__('Content block does not exists, make sure selector is correct. Current selector: %s', 'infinite'), $content_block)); ?>'); } if(!$('<?php echo $listings_parent_block; ?>').length) { console.log('<?php echo osc_esc_js(sprintf(__('Listing parent block does not exists, make sure selector is correct. Current selector: %s', 'infinite'), $content_block)); ?>'); } if(!$('<?php echo $pagination_block; ?>').length) { console.log('<?php echo osc_esc_js(sprintf(__('Pagination block does not exists, maybe there are no other pages. Make sure selector is correct. Current selector: %s', 'infinite'), $pagination_block)); ?>'); } if(!$('<?php echo $pagination_next; ?>').length) { console.log('<?php echo osc_esc_js(sprintf(__('Pagination next button does not exists, maybe there are no other pages. Make sure selector is correct. Current selector: %s', 'infinite'), $pagination_next)); ?>'); } <?php } ?> } </script>
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.