How to make PHP go fine with HTML? - php

I have a index.php page Picture : http://i.imgur.com/UBorPdE.png
Website : http://www.vestigedayz.com/sala/clienti/index.php (User: Test123, pass: test)
<?php include("auth.php"); //include auth.php file on all secure pages )
$dbhost = 'host';
$dbuser = 'user';
$dbpass = 'pass';
$conn = mysql_connect("host", "user", "pass");
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("vestiged_sala")) {
echo "Unable to select vestiged_sala: " . mysql_error();
exit;
}
mysql_select_db("vestiged_sala");
$result = mysql_query("select * from users");
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row["Antrenor"];
echo $row["PrimulContract"];
echo $row["ExpiraContract"];
}
mysql_free_result($result);
?>
ok, after that it comes HTML codes. I have this code
<h4>Bun venit, <?php echo $_SESSION['username']; ?> !
<hr>
Abonamentul tau expira pe data de: <?php echo $row["ExpiraContract"]; ?>
<hr>
Primul tau contract a fost facut pe data de : <?php echo $row["PrimulContract"]; ?>
<hr>
Pe data de <?php echo $row["antrenor"]; ?> va trebui sa platesti instructorul !
</h4>
But php won't show those rows. Only [user] row. The others it appears to be blank. When I add while ($row = mysql_fetch_assoc($result)) above of "Abonamentul tau" it gives me errors. What is the solution to my problem ? Because I know is something easy but I'm beginner and I can't figure it out.

in place of this line
$result = mysql_query("select * from users");
put these lines
$result = mysql_query("SELECT * FROM users WHERE username='$user' LIMIT 1");
while($row = mysql_fetch_array($result)){
$expire = $row['ExpiraContract'];
$primul = $row['PrimulContract'];
$antrenor = $row['Antrenor'];
}
But remember you have to declare empty variables before these line
$user = $_SESSION['username'];
$expire = '';
$primul = '';
$antrenor = '';
So, your full code is like this
//First define empty variables
$user = $_SESSION['username'];
$expire = '';
$primul = '';
$antrenor = '';
// add these lines in place of $result query
$result = mysql_query("SELECT * FROM users WHERE username='$user' LIMIT 1");
while($row = mysql_fetch_array($result)){
$expire = $row['ExpiraContract'];
$primul = $row['PrimulContract'];
$antrenor = $row['Antrenor'];
}
This is you html now
Abonamentul tau expira pe data de: <?php echo $expire; ?>
<hr>
Primul tau contract a fost facut pe data de : <?php echo $primul; ?>
<hr>
Pe data de <?php echo $antrenor; ?> va trebui sa platesti instructorul !
</h4>
Try this. If you have any problem then comment it. :)
Remove these lines if you try this first
while ($row = mysql_fetch_assoc($result)) {
echo $row["Antrenor"];
echo $row["PrimulContract"];
echo $row["ExpiraContract"];
}

Related

What did i do wrong? Html is confusing itself

I'm making a page where you have to enter a text in a textbox and the click send, another page will save it.
Also, on the first page, the text that was stored previously in the database, has to load. This is the code that i've got:
<?php
$databaseid = 3;
$servername = "jog4fun.be.mysql";
$username = "jog4fun_be";
$password = "****";
$dbname = "jog4fun_be";
$gettitel1 = null;
$gettext1 = null;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Id,Titel,Tekst FROM Teksten";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if ($row["Id"]== $databaseid ){
$gettitel1 = $row["Titel"];
$gettext1 = $row["Tekst"];
}
}
} else {
echo "0 results";
}
$conn->close();
$gettitel1 = strip_tags($gettitel1, '<br>');
$link1 = '<textarea id = "klein" rows="4" cols="50" name="titel3" form="usrform">' . $gettitel1 . '</textarea>';
$link2 = '<textarea id = "groot" rows="4" cols="50" name="text3" form="usrform">' . $gettext1 . '</textarea>';
echo $link1;
echo $link2;
?>
The problem is that it sends the text from textbox with name text3 as text1 with the post function. Can someone figure out what's wrong with it? I've been tying for an hour and i did not find it.
Thanks for your time and help,
Jonas
Simply here:
while($row = $result->fetch_assoc()) {
if ($row["Id"]== $databaseid ){
$gettitel1 = $row["Titel"];
$gettext1 = $row["Tekst"];
}
you overwrite the value of the two variables each time you iterate. So after this block of code you will keep stored the last values returned from the db.
YOu should add to your query a WHERE clause to identify the one and only record you need so you will fetch only the relevant data. Example:
$sql = "SELECT Id,Titel,Tekst FROM Teksten WHERE Id='1'";

DropDown to select data from MS SQL server

I'm trying to make a PHP web application display the data from specific Countries from a dropdown but I can't figure it out how to use the WHERE [Column] = [Value1, Value2, Value3] on a PHP dropdown.
I'm using the "Adventure Works 2014 Full Database Backup" for test purpose.
<html>
</body>
<!-- form for tower selection -->
<form action="test20.php" method="POST">
Please select the tower you are about to work on. </br></br>
<select name="TowerSelect"><option> Choose </option>
<?php
$serverName = 'SERVERNAME';
$uid = 'USERNAME';
$pwd = 'PASSWORD';
$databaseName = 'AdWorks';
$connectionInfo = array( 'UID'=>$uid,
'PWD'=>$pwd,
'Database'=>$databaseName);
$conn = sqlsrv_connect($serverName,$connectionInfo);
if($conn){
echo '';
}else{
echo 'Connection failure<br />';
die(print_r(sqlsrv_errors(),TRUE));
}
$sql = "SELECT BusinessEntityID, FirstName FROM dbo.vKelvin WHERE CountryRegionName = 'United States'";
$result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
while ($data=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
echo "<option value=";
echo $data['BusinessEntityID'];
echo ">";
echo $data['BusinessEntityID'];
echo "</option>";
}
?>
<input type="submit" value="Select Tower">
</select></br></br>
</form>
</body></html>
<?php
if(empty($_POST['TowerSelect'])){
$_SESSION['tower'] = '';
} else {
$_SESSION['tower'] = $_POST['TowerSelect'];
echo "<tr>";
echo $_SESSION['tower'];
echo " selected. </p>";
echo('<td>'.$row['BusinessEntityID'].'</td><td>'.$row['FirstName'].'</td></tr>');
}
I believe I have this fixed. There were a number of problems with the code. You were referencing a $row but there was no SQL query that would have resulted in a $row, you were trying to post data after the closing HTML tag, you were trying to create rows for a table without declaring the table, and a few other things. Some of this was probably a result of quickly creating the test case. No problem. Try this...
<?php
$serverName = 'SERVERNAME';
$uid = 'USERNAME';
$pwd = 'PASSWORD';
$databaseName = 'AdWorks';
$connectionInfo = array( 'UID'=>$uid,'PWD'=>$pwd,'Database'=>$databaseName);
$conn = sqlsrv_connect($serverName,$connectionInfo);
if($conn){echo '';}else{echo 'Connection failure<br />';die(print_r(sqlsrv_errors(),TRUE));}
?><html><body>
<!-- form for tower selection -->
<form action="test20.php" method="POST">
Please select the tower you are about to work on. </br></br>
<select name="TowerSelect"><option> Choose </option>
<?php
$sql = "SELECT BusinessEntityID, FirstName FROM dbo.vKelvin WHERE CountryRegionName = 'United States'";
$result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
while ($data=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
echo '<option value="'.$data['BusinessEntityID'].'">';
echo $data['BusinessEntityID'];
echo "</option>";
}
?><input type="submit" value="Select Tower">
</select></br></br>
</form>
<table cols="3" cellpadding="0" cellspacing="0" border="0">
<?php
if(empty($_POST['TowerSelect'])){
$_SESSION['tower'] = '';
} else {
$sql = "SELECT BusinessEntityID, FirstName FROM dbo.vKelvin WHERE BusinessEntityID = '".$_POST['TowerSelect']."'";
$result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
while ($row=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
$_SESSION['tower'] = $_POST['TowerSelect'];
echo '<tr><td>'.$_SESSION['tower'].' selected.</td>';
echo '<td>'.$row['BusinessEntityID'].'</td>';
echo '<td>'.$row['FirstName'].'</td></tr>';
}
}
?></table></body></html>
Note: Though not important to answer your question, it is a best practice to use PDO and bound paramters when making database calls to protect yourself against SQL injection and other nasties. I recommend you look into it to protect your database. Cheers!
Ok, I got the solution, my select was wrong
$sql = "SELECT DISTINCT CountryRegionName FROM dbo.vKelvin ORDER BY CountryRegionName";
$result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
while ($data=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
echo '<option value="'.$data['CountryRegionName'].'">';
echo $data['CountryRegionName'];
echo "</option>";
if(empty($_POST['TowerSelect'])){
$_SESSION['tower'] = '';
} else {
$sql = "SELECT BusinessEntityID, FirstName FROM dbo.vKelvin WHERE BusinessEntityID = '".$_POST['TowerSelect']."'";
$result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
while ($row=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
$_SESSION['tower'] = $_POST['TowerSelect'];
echo '<tr><td>'.$_SESSION['tower'].' selected.</td>';
echo '<td>'.$row['BusinessEntityID'].'</td>';
echo '<td>'.$row['FirstName'].'</td></tr>';
}
}

Image Click Counter, data base Row update, and Order by hits

Im trying to make an image click counter, so that when some one click on an image it updates hit column by 1.
Im having trouble with the syntax, as far as getting the row number that needs to be updated.
Later i want to use this hit column to sort the order that the images are displayed on the site.
If you feel like throwing me a bone and telling how to do that as well it would be much appreciated :)
connect.php
<?php
$servername = "*******";
$username = "********";
$password = "********";
$dbname = "********";
$conn = new mysqli($servername, $username, $password,$dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "Connected successfully";
?>
art.php
<?php
require 'connect.php';
$sql = "SELECT * FROM art";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo
"<div class='art'>
<a href='img/".$row["name"].".jpg '
//part that I need help with
onclick='
<?php
include 'update_hits.php';
update_hit('$row');
?>'
target='_blank'>
<img src='img/".$row["name"]."_tnail.jpg' alt='".$row["name"]."' title='".$row["name"]." • ".$row["year"]." • ".$row["type"]."'/>
</a>
<p>
".$row["name"]." • ".$row["year"]." • ".$row["type"]."
</p>
</div>"
;
}
} else {
echo "0 results";
}
$conn->close();
?>
update_hits.php
<?php
require 'connect.php';
function update_hit($row){
$query = "SELECT 'hits' FROM 'art'";
if(#$query_run = mysql_query($query);){
$count = mysql_result($query_run, '$row' , 'hits');
$count_inc = $count + 1;
$query_update = "UPDATE 'art' SET 'hits' = '$count_inc'";
#$query_update_run =mysql_query($query_update);
}
}
?>
Finally got it to work
<?php
require 'connect.php';
$image = $_GET['image'];
//need to check whether file exists also
if(!empty($image)){
echo "<img src='".$image.".jpg'>"; // prefix full path if needed
$imagename = explode("/", $image);
$sql = "UPDATE `art` SET `hits`=`hits` +1 WHERE `name` = '".$imagename[1]."'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
}
?>
This is only the logic, your code is not perfect it needs many validation and additional checks. I have not tested this code check for syntax errors. Its only for you to get the logic on how to do this.
modified art.php
<?php
require 'connect.php';
$sql = "SELECT * FROM art";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo
"<div class='art'>
<a href='displayImg.php?image=".$row["name"]."' target='_blank'>
<img src='img/".$row["name"]."_tnail.jpg' alt='".$row["name"]."' title='".$row["name"]." • ".$row["year"]." • ".$row["type"]."'/>
</a>
<p>
".$row["name"]." • ".$row["year"]." • ".$row["type"]."
</p>
</div>"
;
}
} else {
echo "0 results";
}
$conn->close();
?>
new displayImg.php
<?php
require 'connect.php';
$image = $_GET['image'];
//need to check whether file exists also
if(!empty($image)){
echo 'img/'.$image.'jpg'; // prefix full path if needed
$sql = "UPDATE 'art' SET hits=hits+1 where name = ".$image;
$result = $conn->query($sql);
}
?>

how to display an auto increment value in a textbox using session

Login.php
session_start();
<?php
$username = "root";
$password = "tiger";
$hostname = "localhost";
//connection to the database
$dbhandle = mysqli_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
/* #var $selected type */
$selected = mysqli_select_db($dbhandle,"sample")
or die("Could not select sample");
$name=(\filter_input(\INPUT_POST,'name'));
$phone=(\filter_input(\INPUT_POST,'phone'));
$email=(\filter_input(\INPUT_POST,'email'));
//$custno=(\filter_input(\INPUT_POST,'custno'));
if(!empty(\filter_input(\INPUT_POST,'continue')))
{
echo "<script type='text/javascript'>\n";
'check()';
echo "</script>";
$sql="insert into customersignin(name,phone,email)values('$name','$phone','$email')";
$result=mysqli_query($dbhandle,$sql) or die(\mysqli_error($dbhandle));
}
else
{
$sql1="insert into customersignin(custno)values(NULL)";
$result1=mysqli_query($dbhandle,$sql1) or die(\mysqli_error($dbhandle));
}
$sql2="select custno from customersignin";
$result2=mysqli_query($dbhandle,$sql2) or die (mysqli_error($dbhandle));
$row= mysqli_fetch_array($result2);
if(mysqli_num_rows($result2)>0)
{
echo "$_SESSION['custno']";
unset($_SESSION['custno'];
header('Location:customersvsoup.php');
}
mysqli_close($dbhandle);
$_SESSION[name]=(\filter_input(INPUT_POST,'name'));
customer.php
<body>
<?php session_start(); ?>
<input type="text" style="position: absolute;top:200px;" value="<?php echo $_SESSION["custno"]?>">
</body>
In the php file the customer log in is done,the custno is the auto generate field,i have 2 buttons called continue and skip,for both the auto generate works fine,after any of the button action is done,i need to display the custno in the text box of the next page using session.But the problem is the text box is empty when i run this code.But the session['name'] is working..Please help.
Your session_start(); should come at the beginning of the file in login.php. I see you using $_SESSION[custno] before it's called. That's why your textbox is empty.
Also it should be:
$_SESSION['custno']
$_SESSION['name']note the single quotes
Regarding your logical problem (in the comments) try:
$_SESSION['name'] = (filter_input(INPUT_POST, 'name'));
if (!empty(filter_input(INPUT_POST, 'continue')))
{
echo "<script type='text/javascript'>\n";
'check()';
echo "</script>";
$sql = "insert into customersignin(name,phone,email)values('$name','$phone','$email')";
$result = mysqli_query($dbhandle, $sql) or die(mysqli_error($dbhandle));
$sql2 = "select max(custno) as last_custno from customersignin";
$result2 = mysqli_query($dbhandle, $sql2) or die(mysqli_error($dbhandle));
if (mysqli_num_rows($result2) > 0)
{
$row = mysqli_fetch_assoc($result2);
$_SESSION['custno'] = $row['last_custno'];
header('Location:customersvsoup.php');
}
}
else
{
$sql1 = "insert into customersignin(custno)values(NULL)";
$result1 = mysqli_query($dbhandle, $sql1) or die(mysqli_error($dbhandle));
//since this bit of code is repeating,
//you could even use a function to shorten it
$sql2 = "select max(custno) as last_custno from customersignin";
$result2 = mysqli_query($dbhandle, $sql2) or die(mysqli_error($dbhandle));
if (mysqli_num_rows($result2) > 0)
{
$row = mysqli_fetch_assoc($result2);
$_SESSION['custno'] = $row['last_custno'];
header('Location:customersvsoup.php');
}
}
And please put the session_start(); inside after <?php. All php code should be within the PHP tags.
you have error in insert query:
$sql="insertintocustomersignin(name,phone,email)values('$name','$phone','$email')";
should be :
$sql="insert into customersignin(name,phone,email) values ('$name','$phone','$email')";
you should use quotes in array index :
$_SESSION[custno], $_SESSION[name] should be $_SESSION['custno'], $_SESSION['name']

Issue with Php And utf8 inserting to mysql [duplicate]

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.

Categories