here is what I want but cannot make it work with the new MySQLi just because my host does not have all new php etc...
But there must be some kind of solution or thats all MYSQLI can do ?
Please dont talk about PDO because even the ugly name sounds like PEDO and I am only interested in MySQLI and a solution for this simple thing. Please dont change the structure of my script. The question is only is if there is something to make it work with MySQL or if I maybe switch back to MySQL procedure instead of statements
<?php
$sql = new mysqli('localhost','user','pass','db');
$who = $_GET['user'];
$query = $sql->prepare("SELECT * FROM profiles WHERE user=?");
$query->bind_param("s",$who);
$result = $query->execute();
while($row = $result->fetch_array(MYSQLI_ASSOC)) // << HERE IS THE PROBLEM //
// I GET ERROR Fatal error: Call to a member function fetch_array() on a non-object in ... //
"" but there must be some way to make it work like we do with while($row = mysqli_fetch_array($sql)) //
{
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>title</title>
</head>
<body>
CUSTOM HTML FOR A NICE DESIGN I WANT TO KEEP THE SAME DESIGN LAYOUT ETC...
HELLO <?php echo "$row[USERNAME]"; ?>
YOUR INFO IS <?php echo "$row[JUST_SOME_INFO]"; ?>
</body>
</html>
<?php
}
?>
Here is your solution
You don't have to use fetch_array() but use fetch()
also you will have to bind result using bind_result before fetch
$query->execute();
$query->bind_result($col1);
while($row = $query->fetch()){
printf("%s \n", $col1);
}
You can use $col1 directly also, no need to use it with printf()
My working example according to my db is given below if you want more assistance,
$sql = new mysqli('localhost','user','pass','dbname');
$who = 'php';
$query = $sql->prepare("SELECT * FROM job WHERE skill=?");
$query->bind_param("s",$who);
$query->execute();
$query->bind_result($col1);
while($row = $query->fetch()){
printf("%s \n", $col1);
}
Comment this string:
$result = $query->get_result();
you don't need this.
Try this one.
<?php
$sql = new mysqli('localhost', 'user', 'pass', 'db');
$who = $_GET['user'];
$query = $sql->prepare("SELECT * FROM profiles WHERE user=?");
$query->bind_param("s", $who);
$result = $query->execute() or die($query->error);
while ($row = $result->fetch_array()) {
$username = $row[USERNAME];
$info = $row[JUST_SOME_INFO];
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>title</title>
</head>
<body>
CUSTOM HTML FOR A NICE DESIGN I WANT TO KEEP THE SAME DESIGN LAYOUT ETC...
HELLO <?php echo $username; ?>
YOUR INFO IS <?php echo $info; ?>
</body>
</html>
This is what happens when you start copying and pasting php together without knowing what it means.
the solution here is:
create a class for $sql or declare $sql a global imediately after calling the variable.
try
global $sql;
but if you actually want to fix the problem(by making your $sql variable an object)
try
$sql = array();
$sql['host'] = 'host';
$sql['user'] = 'user';
$sql['pass'] = 'password';
$sql['db'] = 'database';
global $sql;
$db = new mysqli($sql);
Now when you wanna do something with the db connection.
$db->action();
this is just the basics and probably won't work. you probably should instead read more on php/mysqli before attempting to write your own classes.
Related
I have an existing SHTML page with a few INCLUDE statements for menu's. This has worked well. To this point, my .htaccess file has looked like:
Options +FollowSymLinks
And my Include statement looked like this:
<!--#include virtual="menu_primary.shtml" -->
I have a new need to add some PHP code to the main page. The PHP code queries a Mysql database to return a single row. If the row exists in the database, I want to show it on the SHTML page. If the row does not exist, do nothing. Here's the PHP code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$dbname = "mydbname";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT notice from notification where page = 'home'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "Message is: " . $row["notice"]. "<br>";
}
} else {
echo "";
}
mysqli_close($conn);
?>
</body>
</html>
When I implemented this PHP code, the page seemed to interpret everything after the Greater Than symbol as text. When I posted that problem, someone on this forum suggested altering the .htaccess file to include a PHP parser. For a while. I altered my .htaccess file to look like this:
Options +FollowSymLinks
<FilesMatch "\.(htm|html|shtm|shtml)$">
SetHandler application/x-httpd-php5
</FilesMatch>
However when I do that, the PHP code works fine and I display the data from the database on the SHTML page, but the #Include statements no longer work. How can I enable both the PHP and #Include code together in the same SHTML page? Thanks very much for looking at this.
In your PHP script you can invoke the virtual function to work with your SSI
<?php
virtual('menu_primary.shtml');
There's a very old page that talks about this in more detail
http://www.zytrax.com/tech/php/php_ssi.htm
I have a form with PHP that saves a variable to a MySQL database. That form worked on a VPS, but when trying it on another VPS it gives an error when trying to write to the database when the field contains a ' character. So the same PHP code works on 1 VPS when the field contains a ' character, but not on the other VPS.
Here it works: http://www.zoekmachineoptimalisatie.us/test.php
and here (it's the other VPS) it gives an error: http://www.onzebruidsfotograaf.nl/test.php
My form:
<?php
$hostname = "localhost"; //host name
$dbname = "xxxxxxxx"; //database name
$username = "xxxxxxxx"; //username you use to login to php my admin
$password = "xxxxxxxx"; //password you use to login
$conn = new MySQLi($hostname, $username, $password, $dbname);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Untitled Document</title>
</head>
<body>
<?php
if (isset($_POST['Submit'])) { //if the submit button is clicked
$title = $_POST['updatetitle'];
$bookid = 1;
$update = "UPDATE test SET Title='$title' WHERE BookID = " . $bookid;
$conn->query($update) or die("Cannot update"); //update or error
}
?>
<?php
$bookid = 1;
$sql = "SELECT * FROM test WHERE BookID = '" . $bookid . "'";
$result = $conn->query($sql) or die(mysql_error());
$query = getenv(QUERY_STRING);
parse_str($query);
?>
<h2>Update Record <?php echo $bookid;?></h2>
<form action="" method="post">
<?php
while ($row = $result->fetch_assoc()) {
?>
<textarea name="updatetitle" cols="100" rows="30"><?php echo $row['Title']; ?></textarea>
<table border="0" cellspacing="10">
<tr>
<td><INPUT TYPE="Submit" VALUE="Update the Record" NAME="Submit"></td>
</tr>
</table>
<?php
}
?>
</form>
<?php
if ($update) { //if the update worked
echo "<b>Update successful!</b>";
}
?>
</body>
</html>
An unescaped quote in your query will produce a syntax error. Instead of building the SQL fully your own, make use of SQL variables for your PHP variables with a Prepared Statement:
if (isset($_POST['Submit'])) { //if the submit button is clicked
$title = $_POST['updatetitle'];
$bookid = 1;
$update = $conn->prepare('UPDATE test SET Title = ? WHERE BookID = ?;');
$update->bind_param('sd', $title, $bookid);
$update->execute();
}
One of your servers has Magic Quotes enabled and the other doesn't. Magic Quotes is now considered undesirable and is deprecated, it automatically escapes input. You should turn off Magic Quotes and use a parameterised query/prepared statement instead - then there is no need to escape anything and it prevents SQL Injection.
Paramterised queries are supported by the MySQLi and PDO APIs.
because the single quote breaks the query statement. In order to prevent from it or from SQL Injection you need to use PDO or MySQLI extension. For more infor, see the article below
How can I prevent SQL injection in PHP?
I have managed to get part of this code working.
The variables will echo without problem but as soon as I try and put them into the javascript tag they stop working.
What am I doing wrong??
<?php
$id_1 = $_GET['id'];
$tag_id = "tag_id";
$Activity_Tag_String = "Activity_Tag_String";
$group_tag_string = "group_tag_string";
$link = mysqli_connect("localhost", "username", "password", "database");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT $tag_id, $Activity_Tag_String, $group_tag_string, advertiser_id FROM tbl_tags WHERE advertiser_id = '$id_1'";
$result = mysqli_query($link, $query);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Mate Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
var branch = window.location.href;
var axel = Math.random() + "";
var a = axel * 10000000000000;
document.write('<iframe src="http://fls.doubleclick.net/activityi;src=<?php $tag_id?>;type=<?php $Activity_Tag_String?>;cat=<?php $group_tag_string?>;u1='';ord=' + a + '?" width="1" height="1" frameborder="0" style="display:none"></iframe>');
</script>
</body>
</html>
<?php $tag_id?>
should be
<?= $tag_id ?>
or
<?php echo $tag_id ?>
Your version is simply doing the PHP equivalent of:
$tag_id;
which is a do-nothing statement. You need to actually echo that variable's contents.
As well, note that your code is vulnerable to SQL injection attacks, and you should fix that before you do anything else.
for js script part try:
<?php echo $variable;?>
or in short
<?=$var?>
i am just a beginner and simply trying to read data from a db.there are 2 files, one is include file which contains db connection code and another the 2nd part of my given below code.In db, 3 columns there: 1.id, 2.name and 3. description when i try to open the located folder in firefox it shows
"Fatal error: Call to undefined
function mysql_fetch_arrey() in
C:\xampp\htdocs\www\database
connection\index.php on line 8"
the 8 num line is
"while($person =
mysql_fetch_arrey($result))"
i am checked the "mysql_fetch_arrey($result)" with "$mysql_fetch_arrey($result)"
but it shows
"Fatal error: Function name must be a
string in C:\xampp\htdocs\www\database
connection\index.php on line 8"
i use adobe dreamwaver5 and xampp server
1st page :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>connection</title>
</head>
<body>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = 'db_connection';
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($db);
?>
</body>
</html>
</body>
</html>
2nd page :
<?php
include 'connection.php';
$query = "SELECT * FROM people";
$result = mysql_query($query);
while($person = $mysql_fetch_arrey($result))
{
echo "<h3>".$person['name']."</h3>";
echo "<p>".$person['description']."</p>";
}
?>
The function's name is mysql_fetch_array, not mysql_fetch_arrey. So your while loop should like:
while($person = $mysql_fetch_array($result)) {
....
}
Typo here $mysql_fetch_arrey
This should be
while($person = mysql_fetch_array($result))
I am trying to get my custom sessions working but my variables do not persist from page to page. If I remove the require line and replace it with session_start(); it works fine. All of these files are in the same directory and I have session.save_handler set to user in my php.ini file.
first HTML page
<?php
require("sessionSetup.php");
$_SESSION['test'] = "session test";
session_regenerate_id();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>sessions test</title>
<script type="text/javascript">
<!--
alert("Test: <?php echo $_SESSION['test'];?>");
//-->
</script>
</head>
<body>
Click here to go to session2.
</body>
</html>
second HTML page
<?php
require("sessionSetup.php");
//session_start();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>sessions test</title>
<script type="text/javascript">
<!--
alert("Test: <?php echo $_SESSION['test'];?>");
//-->
</script>
</head>
<body>
Click here to go to session.
</body>
</html>
sessionSetup.PHP
<?php
session_set_save_handler('_open','_close','_read','_write','_destroy','_clean');
session_start();
function _open(){
global $_sess_db;
if($_sess_db = mysql_connect(host,user,password)){
return mysql_select_db(db, $_sess_db)or die("cannot select DB");
}
return false;
}
function _close(){
global $_sess_db;
return mysql_close($_sess_db);
}
function _read($id){
global $_sess_db;
$id = mysql_real_escape_string($id);
$sql = "SELECT data FROM session WHERE id = '$id'";
if ($result = mysql_query($sql, $_sess_db)) {
if (mysql_num_rows($result)) {
$record = mysql_fetch_assoc($result);
return $record['data'];
}
}
return '';
}
function _write($id, $data){
global $_sess_db;
$access = time();
$id = mysql_real_escape_string($id);
$access = mysql_real_escape_string($access);
$data = mysql_real_escape_string($data);
$sql = "REPLACE INTO session VALUES ('$id', '$access', '$data')";
return mysql_query($sql, $_sess_db);
}
function _destroy($id){
global $_sess_db;
$id = mysql_real_escape_string($id);
$sql = "DELETE FROM session WHERE id = '$id'";
return mysql_query($sql, $_sess_db);
}
function _clean($max){
global $_sess_db;
$old = time() - $max;
$old = mysql_real_escape_string($old);
$sql = "DELETE FROM session WHERE access < '$old'";
return mysql_query($sql, $_sess_db);
}
?>
I have replace the database login stuff with dummy information here. Also when I check with phpadmin there is no info in my sessions db. All I get on the second HTML page is a null value. I have been working on this for a while now and have made no progress. Any help I could get wiould be greatly appreciated.
The code looks ok.
Make sure your database table used for storing session data is correctly set up, because session handler functions don't seem to have any error checking.
The most probable cause of your sessions not working is either id or data column of session table not big enough to hold full info. Access should be int, try different sizes of varchar for id and data.
As emphasized in the php manual page on session_start() it MUST go before anything is outputted to the browser. Most likely your required file (sessionSetup.php) has a couple empty bits at the beginning or end which are not being interpreted as php and therefore being outputted to the bowser. To fix this simply put session_start before require("sessionSetup.php"); (also don't forget to remove session_start from your session setup file once you do that). OR you could create an output buffer.