what is the best way to direct the user to another page given the IF statement is true. i want the page to direct the user to another page using PHP, when the IF statement is run, i tired this but it doesn't work??
if ( mysqli_num_rows ( $result ) > 0 )
{
header('Location: exist.php');
die();
}
Below is the full source code for the page.
<?php
// starts a session and checks if the user is logged in
error_reporting(E_ALL & ~E_NOTICE);
session_start();
if (isset($_SESSION['id'])) {
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
} else {
header('Location: index.php');
die();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<p><span>Room No: </span><?php $room = $_SESSION['g'];
echo $room; // echo's room ?>
</p>
<p><span>Computer No: </span><?php
$select3 = $_POST['bike'];
echo $select3;
?>
</p>
<p><span>Date: </span><?php $date = $_POST['datepicker'];
echo $date; // echo's date
?>
</p>
<p><span>Start Session: </span>
<?php
if(isset($_POST['select1'])) {
$select1 = $_POST['select1'];
echo $select1;
echo "";
}
else{
echo "not set";
}
?>
</p>
<p><span>End Session: </span>
<?php
if(isset($_POST['select2'])) {
$select2 = $_POST['select2'];
echo $select2;
echo "";
}
else{
echo "not set";
}
?>
</p>
</div>
<div id="success">
<?php
$servername = "localhost";
$name = "root";
$password = "root";
$dbname = "my computer";
// Create connection
$conn = mysqli_connect($servername, $name, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$query = "SELECT * FROM `booked` WHERE
`date` = '{$date}' AND
`computer_id` = '{$select3}' AND
`start_time` = '{$select1}' AND
`end_time` = '{$select2}' AND
`room` = '{$room}'
";
$result = mysqli_query($conn, $query);
if ( mysqli_num_rows ( $result ) > 0 )
{
header('Location: exist.php');
die();
}
else
{
$sql = "INSERT INTO booked (date, computer_id, name, start_time, end_time, room)
VALUES ('$date', '$select3', '$username', '$select1', '$select2', '$room')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
</div>
<form action="user.php">
<input type="submit" value="book another" class="bookanother" />
</form>
</div>
</body>
</html>
If the header is sent already, for example you have echo something before then the header will not work, because the header cannot be set after data flow has started, (since php would have already set the default headers for you). So, in this case if that is so, I do the redirect using javascript.
PHP Docs:
Remember that header() must be called before any actual output is
sent, either by normal HTML tags, blank lines in a file, or from PHP.
It is a very common error to read code with include, or require,
functions, or another file access function, and have spaces or empty
lines that are output before header() is called. The same problem
exists when using a single PHP/HTML file.
WORK-AROUND: This is a function I have written long back and include in controllers.
/**
* Safely redirect by first trying header method but if headers were
* already sent then use a <script> javascript method to redirect
*
* #param string
* #return null
*/
public function safeRedirect($new_url) {
if (!headers_sent()) {
header("Location: $new_url");
} else {
echo "<script>window.location.href = '$new_url';</script>";
}
exit();
}
add the function and simply call:
safeRedirect('index.php');
Related
Hi im trying to delete a users booking detials when the user clicks delete in my bookingbeforedeltion.php file but for some reason when I test my php file once I click delete it goes to my delete.php screen and says it failed to delete from database and has the error Undefined index: rn. Is my rn not defined? Sorry Im new to this. Here is my code below:
bookingbeforedeltion.php:
<!DOCTYPE HTML>
<html><head><title>BookingBeforeDeletion</title> </head>
<body>
<?php
include "config.php";
$DBC = mysqli_connect("127.0.0.1", DBUSER , DBPASSWORD, DBDATABASE);
if (!$DBC) {
echo "Error: Unable to connect to MySQL.\n".
mysqli_connect_errno()."=".mysqli_connect_error() ;
exit;
};
echo "<pre>";
$query = 'SELECT roomname, checkindate, checkoutdate FROM booking';
$result = mysqli_query($DBC,$query);
if (mysqli_num_rows($result) > 0) {
echo "Delete Bookings" ?><p><?php
while ($row = mysqli_fetch_assoc($result)) {
echo "Room name: ".$row['roomname'] . PHP_EOL;
echo "Check in date: ".$row['checkindate'] . PHP_EOL;
echo "Check out date: ".$row['checkoutdate'] . PHP_EOL;
?>
[Cancel]
<?php
echo "<hr />";
}
mysqli_free_result($result);
}
echo "</pre>";
echo "Connectted via ".mysqli_get_host_info($DBC);
mysqli_close($DBC);
?>
</body>
</html>
delete.php:
<!DOCTYPE HTML>
<html><head><title>BookingBeforeDeletion</title> </head>
body>
<?php
include "config.php";
$DBC = mysqli_connect("127.0.0.1", DBUSER , DBPASSWORD, DBDATABASE);
if (!$DBC) {
echo "Error: Unable to connect to MySQL.\n".
mysqli_connect_errno()."=".mysqli_connect_error() ;
exit;
};
echo "<pre>";
$roomname=$_GET['rn'];
$query = "DELETE bookingID, roomname, checkindate, checkoutdate, contactnumber,
bookingextras, roomreview, customerID, roomID FROM booking WHERE roomname =
'$roomname'";
$result = mysqli_query($DBC,$query);
if($result)
{
echo "<font color='green'> Booking deleted from database";
}
else {
echo "<font color='red'> Failed to delete booking from database";
}
?>
and I think this will help:
As mentioned above, you need to print it from the PHP
<a href= 'delete.php?rn=$result[roomname]'>
// To
<a href= 'delete.php?rn=<?= $row['roomname'] ?>'>
// Explanation:
// 1. <?= ... ?> is the short form of <?php echo ... ?>
// 2. The `roomname` came from $row, not $result ($result is the MySQLi Object)
// 3. You need to quote the `roomname` because without it `roomname` will be readed
// as Constant, and may Throw a Warning message
//
Your DELETE is incorrect, the correct one is DELETE FROM ... WHERE ...
$query = "DELETE bookingID, roomname, checkindate, checkoutdate, contactnumber,
bookingextras, roomreview, customerID, roomID FROM booking WHERE roomname =
'$roomname'";
// To
$query = "DELETE FROM booking WHERE roomname = '$roomname'";
EXTRA:
3. You can assign a default value to $roomname
$roomname=$_GET['rn'];
// To
$roomname=$_GET['rn'] ?? 'default if null';
// if the rn index doesnt exist, the $roomname value will be `default if null` instead of throwing a Warning
Try to use Prepared-Statement SQL instead of writing it. (I dont know the example, but it can prevent SQL Injection)
The page is unable to see the login form whose code is written under the isset function statement. I have written the code correctly and have executed it many times , but now the code written inside the isset statement does not works. here is the code:-
<?php
session_start();
echo "<p style=\"font-color: #ff0000;\"> Catogoies </p>";
echo '<link href="var/www/html/sample.css" rel="stylesheet">';
require_once('../html/conn.php');
$query = "select * from catogories";
mysqli_select_db($dbc, 'odit');
$retrieve = mysqli_query($dbc, $query);
if(!$retrieve)
{
die(mysqli_error($query));
}
while($row=mysqli_fetch_array($retrieve, MYSQL_ASSOC)){
echo "<p style=\"font-color: #ff0000;\">".''.$row["Name"].''."</p>";
$_SESSION['cat']=$row["Name"];
}
if(!($_SESSION)) {
session_start();
}if(isset($_SESSION['lgout']))//the variable logout intialization line
{
if($_SESSION['lgout']!=1||$_SESSION['signup']){
echo "Hello : ".''.$_SESSION['unme'].''; echo "<br><br>";
echo '<a href="logout.php">'."Logout";}
else {
include 'lform.php'; echo "<br><br>";
echo '<a href="Sign_up.php">'."Sign up"."<br>";
} }
mysqli_close($dbc);
//include 'lform.php';
?>
<br>
<a href = 'adding_catogory.php'>Create a New Catogory</a><br><br>
<a href = 'Log_in.php'></a>
<?php
$db = #mysqli_connect("localhost", "oddittor", "Odit#123", "odit");
if(isset($_POST['login'])){
$username=mysqli_real_escape_string($db, $_POST['l_id']);
$password=mysqli_real_escape_string($db, $_POST['pswd']);
$sql="SELECT * from users where usrName='$username' and pswrd = '$password'";
$result = mysqli_query($db, $sql) or die(mysqli_error($db));
$count=mysqli_num_rows($result) or die(mysqli_error($db));
if($count>0) {
$_SESSION['unme']=$username; //This is the global session variable...used for storing the variables across the pages.
$_SESSION['lgout']=0;
header('Location : session.php'.$_SESSION['unme']);
header("Location : Homepage.php".$_SESSION['unme'].$_SESSION['lgout']); header( "refresh:0;url=Homepage.php" );
$_SESSION['unme']=$username;
}
else {
$error = "Invalid Details! Please Renter them"; }
}
?>
Here the problem is in the
if(isset($_SESSION['lgout']))
line if, I remove this line i can see the login page form but by doing so, I get the error of undefined variable logout whenever, I open the page for the first time.
here is the logout script
<html>
<?php
session_start();
$_SESSION['lgout']=1;
$_SESSION['signup']=0;
echo ' You have been successfully logged out';
header('Location : Homepage.php'.$_SESSION['lgout']);header( "refresh:0;url=Homepage.php" );
?>
</html>
You need to put your
session_start();
globally on the start of page. As it's not able to get $_SESSION object.
Just remove
session_destroy();
As you can access all $_SESSION values.
Your queries not secured. Use Prepared Statements instead of your all queries.
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
Hello, I've been stumped by the PHP code I've written. I've stared at this for hours with no success, please help find any errors I've apparently gone over.
What I want this script to do is from a html form page, to query a database table ('users') to make sure their password and username are correct, then in a separate table ('tokens') insert a random token (the method I used before, it works) into the 'tk' column, and the users general auth. code pulled from the 'users' table into the 'gauth' colum, in the 'tokens' table.
The reason for the additional general auth is so I can pull their username and display it on all the pages I plan on "securing"
Sorry if I'm confusing, this is the best I can refine it. Also, I'm not that good at formatting :). I'm going to add some html later, that's why the tags are there.
MySQL Tables:
Users Example:
cols: username | password | email | classcode | tcode | genralauth |
hello | world | hello.world#gmail.com | 374568536 | somthin | 8945784953 |
Tokens Example:
cols: gauth | tk |
3946893485 |wr8ugj5ne24utb|
PHP:
<html>
<?php
session_start();
error_reporting(0);
$servername = "localhost";
$username = "-------";
$password = "-------";
$db = "vws";
?>
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<?php
$sql1 = "SELECT username FROM users";
$data1 = $conn->query($sql1);
if ($conn->query($sql1) === TRUE) {
echo "";
}
?>
<?php
$sql2 = "SELECT password FROM 'users'";
$data2 = $conn->query($sql2);
if ($conn->query($sql2) === TRUE) {
echo "";
}
?>
<?php
$bytes = openssl_random_pseudo_bytes(3);
$hex = bin2hex($bytes);
?>
<?php
if($_POST['pss'] == $data2 and $_POST['uname'] == $data1) {
$correct = TRUE;
}
else {
$correct = FALSE;
}
?>
<?php
if ($correct === TRUE) {
$sql3 = "SELECT generalauth FROM users WHERE password='".$_POST['pss']."'";
$result3 = $conn->query($sql3);
}
?>
<?php
if ($correct === TRUE) {
$sql4 = "INSERT INTO tokens (tk,gauth) VALUES (".$hex."' , '".$result3."')";
if ($conn->query($sql4) === TRUE) {
echo "New token genrated.";
} else {
echo "Error: " . $conn->error;
}
}
?>
<?php
if ($correct === TRUE) { ?>
<p>Succesfuly loged in!</p><br/>
<button>Continue</button><br/>
<?php
}
elseif ($correct === FALSE) { ?>
<p>Incorrect, please try again.</p><br/>
<button>Back</button><br/>
<?php
}
?>
<?php
if ($correct === TRUE) {
$_SESSION['auth'] = $hex;
$_SESSION['logstat'] = TRUE;
}
?>
<?php
if ($correct === FALSE) {
$_SESSION['logstat'] = FALSE;
}
$conn->close();
?>
This is the PHP I'm going to use on most pages for token auth, howver it dosn't actually check the database 'tokens', also I need a way to display signed in users username using the general auth.
PHP:
<html>
<h1 class="title">Virtual Work Sheets!</h1>
<p class="h_option">[Log In / Register]</p><hr/>
<div class="body">
<?php
session_start();
error_reporting(0);
$servername = "localhost";
$username = "root20";
$password = "jjewett38";
$db = "vws";
?>
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<?php
$sql = "SELECT tk FROM tokens";
$data = $conn->query($sql);
?>
<?php
if (!$_GET['tk'] == $data) {
echo "
<p>Invalid token, please consider re-logging.</p>
";
}
else {
?>
<?php
switch ($_GET['view']) {
case teacher:
?>
Teacher page html here...
<?php
break;
case student:
?>
Student page html here...
<?php
break;
default:
echo "Please login to view this page.";
}
}?>
</html>
I suggest that you change your approach.
Although at first glance these example files looks like a lot, once you study them you'll see it's really much more simple and logical approach than the direction you are now headed.
First, move the db connect / login stuff into a separate file, and require or include that file at top of each PHP page:
INIT.PHP
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Might as well also load your functions page here, so they are always available
require_once('fn/functions.php');
?>
Now, see how we use it on the Index (and Restricted) pages?
INDEX.PHP
<?php
require_once('inc/head.inc.php');
require_once('fn/init.php');
?>
<body>
<!-- Examples need jQuery, so load that... -->
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<!-- and our own file we will create next... -->
<script type="text/javascript" src="js/index.js"></script>
<div id="pageWrap">
<div id="loginDIV">
LoginID: <input type="text" id="liID" /><br>
LoginPW: <input type="password" id="liPW" /><br>
<input type="button" id="myButt" value="Login" />
</div>
</div>
JS/INDEX.JS
$(function(){
$('#myButt').click(function(){
var id = $('#liID').val();
var pw = $('#liPW').val();
$.ajax({
type: 'post',
url: 'ajax/login.php',
data: 'id=' +id+ '&pw=' +pw,
success: function(d){
if (d.length) alert(d);
if (d==1) {
window.location.href = 'restricted_page.php';
}else{
$('#liID').val('');
$('#liPW').val('');
alert('Please try logging in again');
}
}
});
});//END myButt.click
}); //END document.ready
AJAX/LOGIN.PHP
<?php
$id = $_POST['id'];
$pw = $_POST['pw'];
//Verify from database that ID and PW are okay
//Note that you also should sanitize the data received from user
if ( id and password authenticate ){
//Use database lookups ot get this data: $un = `username`
//Use PHP sessions to set global variable values
$_SESSION['username'] = $un;
echo 1;
}else{
echo 'FAIL';
}
RESTRICTED_PAGE.PHP
<?php
if (!isset($_SESSION['username']) ){
header('Location: ' .'index.php');
}
require_once('inc/head.inc.php');
require_once('fn/init.php');
?>
<body>
<h1>Welcome to the Admin Page, <?php echo $_SESSION['username']; ?>
<!-- AND here go all teh restricted things you need a login to do. -->
More about AJAX - study the simple examples
So as the title suggests, I am having trouble executing a MySQL query. The query works almost successfully, as all data fields are stored into my database except for one. The query itself is a commenting system for signed in users to comment on any given blog post. The issue I am having is that the variable '$post_id' is not recognized, and therefore '$comment_post_ID' is not stored in my database.
'$post_id' is defined in blogs.php, and after echoing this variable it does exist and is successfully defined. However, this variable is not passed onto commentsubmit.php, which is included in the same file where the variable is defined. Why is this happening?
Here are all the pieces of my code:
blogs.php (shows all posts from all users, or just one post if ?id is set in the url. If ?id is set, users can comment on the single post they are viewing.)
<?php
if (isset($_GET['id'])) {
$conn = mysqli_connect("localhost", "root", "mypassword", "mydbname");
if (mysqli_connect_errno($conn)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
$post_id = mysqli_real_escape_string($conn, $_GET['id']);
$blog_post = "SELECT * FROM blogs WHERE id = '$post_id'";
$blog_query = mysqli_query($conn, $blog_post);
while ($row = mysqli_fetch_array($blog_query)) {
$title = $row['title'];
$body = $row['body'];
$author = $row['author'];
$author_username = $row['author_username'];
$datetime = time_ago($row['datetime'], $granularity=2);
}
include ("./fullpageblog.php");
if (isset($_SESSION['id'])) {
include ("./blogcomment.php");
include ("./commentsubmit.php");
}
echo "$post_id";
mysqli_close($conn);
}
?>
blogcomment.php (form for users to make a comment)
<div class="row col-sm-12">
<div id="fullPageBlog">
<div id="center-border"></div>
<form action="commentsubmit.php" method="post">
<textarea maxlength="1000" id="blogComment" name="content" placeholder="Write your response..."></textarea>
<input type="submit" name="comment" value="Publish" />
</form>
<script type="text/javascript">$('#blogPost').elastic();</script>
</div>
</div>
commentsubmit.php (comment query itself)
<?php
session_start();
if (isset($_POST['comment'])) {
$conn = mysqli_connect("localhost", "root", "mypassword", "mydbname");
if (mysqli_connect_errno($conn)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
$comment_post_ID = $post_id;
$comment_author = $_SESSION['full_name'];
$comment_author_email = $_SESSION['email'];
$comment_author_username = $_SESSION['username'];
$comment_date = date("Y-m-d H:i:s");
$comment_content = mysqli_real_escape_string($conn, $_POST['content']);
$user_ID = $_SESSION['id'];
$comment_submit = "INSERT INTO comments (comment_ID, comment_post_ID, comment_author, comment_author_email, comment_author_username, comment_date, comment_content, user_ID) VALUES ('', '$comment_post_ID', '$comment_author', '$comment_author_email', '$comment_author_username', '$comment_date', '$comment_content', '$user_ID') ";
$comment_query = mysqli_query($conn, $comment_submit);
mysqli_close($conn);
header("Location: blogs.php");
die();
}
?>
You don't include/require the blogs.php script from the commentsubmit.php script, so the code in blogs.php would never be run after a POST that is made directly to commentsubmit.php unless you have some other request processing (i.e. a server-side rewrite or similar) that happens automatically on the server before the request ultimately reaches the portion of code shown in commentsubmit.php above.
<?php
$con = mysql_connect("localhost","root","password");
$con=mysql_select_db("database_name");
error_reporting(0);
session_start();
if(isset($_POST["submit"])){
$comment_author = $_POST['full_name'];
$comment_author_email = $_POST['email'];
$comment_author_username = $_POST['username'];
$sql="select * from table_name where `full_name`='"$comment_author "',`email`='"$comment_author_email "',`username`='"$comment_author_username "'";
$qur=mysql_query($sql);
$row= mysql_fetch_array($qur);
$num= mysql_num_rows($qur);
}
if($num>0){
$_SESSION["full_name"]=$full_name;
$_SESSION["email"]=$comment_author_email;
$_SESSION["username"]=$comment_author_username;
}
else{
echo"Username and Password are wrong";
}
?>
This question already has answers here:
Issue with PHP MySQL and insert into UTF-8 [closed]
(3 answers)
Closed 10 years ago.
I have a problem with php & mysql, insert to database using utf-8.
first file:
addsite:
<?php
include 'header.php';
if(isset($data)) {
foreach($_POST as $key => $value) {
$posts[$key] = filter($value);
}
if(isset($posts['type'])){
if($posts['url'] == "http://" || $posts['url'] == ""){
$error = "Add your page link!";
}else if($posts['title'] == ""){
$error = "Add your page title!";
}else if(!preg_match("/\bhttp\b/i", $posts['url'])){
$error = "URL must contain http://";
}else if(!preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $posts['url'])){
$error = "Please do not use special characters in the url.<";
}else{
include "plugins/" . $posts['type'] . "/addsite.php";
}
}
?>
<div class="contentbox">
<font size="2">
<li>Pick the type of exchange you are promoting from the dropdown menu.</li>
<li>Set the amount of coins you wish to give per user complete(CPC).</li>
<li>The higher the amount of coins the higher the Links position.</li>
</div>
<div class="contentbox">
<div class="head">Add Site</div>
<div class="contentinside">
<?php if(isset($error)) { ?>
<div class="error">ERROR: <?php echo $error; ?></div>
<?php }
if(isset($success)) { ?>
<div class="success">SUCCESS: <?php echo $success; ?></div>
<?php }
if(isset($warning)) { ?>
<div class="warning">WARNING: <?php echo $warning; ?></div>
<?php } ?>
<form class="contentform" method="post">
Type<br/>
<select name="type"><?php $select = hook_filter('add_site_select', ""); echo $select; ?></select><br/><br/>
Link<br/>
<input name="url" type="text" value="<?php if(isset($posts["url"])) { echo $posts["url"]; } ?>"/><br/><br/>
Title<br/>
<input name="title" type="text" value="<?php if(isset($posts["title"])) { echo $posts["title"]; } ?>"/><br/><br/>
Cost Per Click<br/>
<?php if($data->premium > 0) { ?>
<select name="cpc"><?php for($x = 2; $x <= $site->premcpc; $x++) { if(isset($posts["cpc"]) && $posts["cpc"] == $x) { echo "<option selected>$x</option>"; } else { echo "<option>$x</option>"; } } ?></select><br/><br/>
<?php }else{ ?>
<select name="cpc"><?php for($x = 2; $x <= $site->cpc; $x++) { if(isset($posts["cpc"]) && $posts["cpc"] == $x) { echo "<option selected>$x</option>"; } else { echo "<option>$x</option>"; } } ?></select><br/><br/>
<?php } ?>
<input style="width:40%;" type="Submit"/>
</form>
</div>
</div>
<?php
}
else
{
echo "Please login to view this page!";
}
include 'footer.php';
?>
second file , plugin addsite.php
<?php
$num1 = mysql_query("SELECT * FROM `facebook` WHERE `url`='{$posts['url']}'");
$num = mysql_num_rows($num1);
if($num > 0){
$error = "Page already added!";
}else if(!strstr($posts['url'], 'facebook.com')) {
$error = "Incorrect URL! You must include 'facebook.com'";
}else{
mysql_query($qry);
mysql_query("INSERT INTO `facebook` (user, url, title, cpc) VALUES('{$data->id}', '{$posts['url']}', '{$posts['title']}', '{$posts['cpc']}') ");
$success = "Page added successfully!";
}
?>
when i write arabic language in the form and submit ,
it went to database with unkown language like :
أسÙ
database collaction : utf8_general_ci
<?php
error_reporting(E_ALL);
ini_set('display_errors', '0');
$host = "localhost"; // your mysql server address
$user = "z*******"; // your mysql username
$pass = "m********"; // your mysql password
$tablename = "z*******"; // your mysql table
session_start();
$data = null;
if(!(#mysql_connect("$host","$user","$pass") && #mysql_select_db("$tablename"))) {
?>
<html>
MSQL ERROR
<?
exit;
}
include_once 'functions.php';
require_once "includes/pluggable.php";
foreach( glob("plugins/*/index.php") as $plugin) {
require_once($plugin);
}
hook_action('initialize');
$site = mysql_fetch_object(mysql_query("SELECT * FROM settings"));
?>
after removing
$posts[$key] = filter($value); "
from header.php
The output shift from:
To:
& Oslash; & pound; & Oslash; ³& Ugrave
to : Ù Ù Ù
header file : http://zwdha.com/header.txt
You might need to add some ini_set statements if your db is full utf8: http://www.polak.ro/php-mysql-utf-8.html
This a very basic insert query to see if you can insert data in you database with PHP.
<?php
function inserting_data() {
$host = "host";
$user = "username";
$password = "password";
$database = "database";
$charset = "utf8";
$link = mysqli_connect($host, $user, $password, $database);
mysql_set_charset($charset, $link);
IF (!$link) {
echo('Unable to connect to the database!');
} ELSE {
/*
* this just to test if something gets inserted into your table.
* If some of your columns are set to not null you should add them tot this insert query.
*/
$query = "INSERT INTO facebook (`title`) VALUES('test_title'), ('test_title1')";
mysqli_query($link, $query);
}
mysqli_close($link);
}
?>
This is a very basic select query to retrieve data form your database.
<?php
function selecting_data(){
$host = "host";
$user = "username";
$password = "password";
$database = "database";
$charset = "utf8";
$link = mysqli_connect($host, $user, $password, $database);
mysql_set_charset($charset, $link);
IF (!$link) {
echo('Unable to connect to the database!');
} ELSE {
/*
* this just to test if something gets returned from your table.
*/
$query = "SELECT * FROM facebook";
$result = mysqli_query($link, $query);
while ($rows = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo $rows['title'];
}
}
mysqli_close($link);
}
?>
My advise is to first test if you can get data in your database and retrieve it. By trial and error you will need to solve your question. B.T.W. I have used MYSQLI_ function instead of MYSQL. The mysql_ functions will depreciate soon. Hope this helps.
a - you should not use mysql_ functions. use PDO. this error is one of the reasons.
b - mysql_set_charset('utf8');
c - are the columns you are trying insert data using utf8_general_ci ?
d - on my.cf set default-character-set and character-set-server
if this doesn't work read this:
http://www.oreillynet.com/onlamp/blog/2006/01/turning_mysql_data_in_latin1_t.html
and this:
http://www.phpwact.org/php/i18n/utf-8
if after that you still dont get it right, make sure to listen to people and use PDO.