I recently switched my code for accessing my database to a PHP PDO Object.
I have everything working accept for my ajax page. As far as I have been able to tell all the queries and data are being pulled out properly, however I get the following error when I try using PDO this was working before with a mysql_connect object.
I did find that if I comment out these lines it will run but then it is unable to run the query which causes more errors obviously.
//ini_set('include_path', 'C:\www\capc\libraries');
//include '/php/capc.php';
//include '/php/bio.php';
Error Message:
This page contains the following errors:
error on line 4 at column 6: XML declaration allowed only at the start of the document
Below is a rendering of the page up to the first error.
CAPC Class query function
public function query($sql) {
try {
$handler = new PDO('mysql:host=' . $this->dbhost . ';dbname=capc', $this->dbuser, $this->dbpass);
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo $e->getMessage();
}
$query = $handler->prepare($sql);
$query->execute();
return $query;
}
Ajax.php
<?php
ini_set('include_path', 'C:\www\capc\libraries');
include '/php/capc.php';
include '/php/bio.php';
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
$bio_first = $_GET['First_Name'];
$bio_last = $_GET['Last_Name'];
if (!empty($bio_first) && !empty($bio_last)) {
$capc = new CAPC;
$sql = 'SELECT Bio_ID FROM `bio_users` WHERE Bio_First = "' . $bio_first . '" AND Bio_Last = "' . $bio_last . '";';
$query = $capc->query($sql);
$num_results = $query->rowCount();
}
echo '<bio>';
if ($num_results > 0) {
$bio_first = $capc->sanitize($bio_first, "string");
$bio_last = $capc->sanitize($bio_last, "string");
$bio = new Bio($bio_first, $bio_last);
echo '<bio_exists>';
echo 'True';
echo '</bio_exists>';
echo '<bio_fname>';
echo $bio->Bio_First;
echo '</bio_fname>';
echo '<bio_lname>';
echo $bio->Bio_Last;
echo '</bio_lname>';
echo '<bio_img>';
echo $bio->Bio_Img;
echo '</bio_img>';
} else {
echo '<bio_exists>';
echo 'False';
echo '</bio_exists>';
}
echo '</bio>';
?>
Finally got it working by moving the include for bio.php not sure why this works now and wouldn't before.
Working Ajax.php
<?php
ini_set('include_path', 'C:\www\capc\libraries');
include '/php/capc.php';
$bio_first = $_GET['First_Name'];
$bio_last = $_GET['Last_Name'];
if (!empty($bio_first) && !empty($bio_last)) {
$capc = new CAPC;
$sql = 'SELECT Bio_ID FROM `bio_users` WHERE Bio_First = "' . $bio_first . '" AND Bio_Last = "' . $bio_last . '";';
$query = $capc->query($sql);
$num_results = $capc->query($sql)->rowCount();
}
if ($num_results > 0) {
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<bio>';
$bio_first = $capc->sanitize($bio_first, "string");
$bio_last = $capc->sanitize($bio_last, "string");
include '/php/bio.php';
$bio = new Bio($bio_first, $bio_last);
echo '<bio_exists>';
echo 'True';
echo '</bio_exists>';
echo '<bio_fname>';
echo $bio->Bio_First;
echo '</bio_fname>';
echo '<bio_lname>';
echo $bio->Bio_Last;
echo '</bio_lname>';
echo '<bio_img>';
echo $bio->Bio_Img;
echo '</bio_img>';
} else {
echo '<bio_exists>';
echo 'False';
echo '</bio_exists>';
}
echo '</bio>';
?>
Related
I am having trouble echoing row data within the page I want to print it out to.
My function works, but only echoes the information because it is local (within the same function).
I'm trying to get this function to echo the database's information to another .php file (same program).
public function findByUsername($username) {
$sql = 'SELECT * FROM events WHERE username=? ';
$statement = DatabaseHelper::runQuery($this->connection, $sql, Array($username));
while ($row = $statement->fetch()) {
echo $row['username'] . "<br />";
echo $row['date'] . "<br />";
}
}
Here is the part of the other file I need to print the information from the function to:
<?php
if (isset($_SESSION["username"])) {
$eventDAO = new EventDAO($connection);
$event = $eventDAO->findByUsername($_SESSION["username"]);
foreach((array)$event as $e) {
echo $e->getUsername() . ' ' . $e->getDate() . '<br>';
}
}
?>
I'm trying to output the username/date.
Not 100% on this concept.
If you're simply trying to output username/date from one file to another, try using sessions.
public function findByUsername($username) {
$sql = 'SELECT * FROM events WHERE username=? ';
$statement = DatabaseHelper::runQuery($this->connection, $sql, Array($username));
while ($row = $statement->fetch()) {
echo $row['username'] . "<br />";
echo $row['date'] . "<br />";
$_SESSION['getuname'] = $row['username'];
$_SESSION['getdate'] = $row['date'];
}
}
You can then output the information on another php file simply by echoing it out.
echo "Username is ". $_SESSION['getuname'];
Im trying to update a database using php.
The site im working on , i have a local copy and a copy on a server.
It works locally , but on the server it shows that it worked , but does not update the database.
I have checked that the id and data variables do actually have a value and teh connection is working.
This is my code :
<?php
include("../../config/connect.php");
if($_GET['id'] and $_GET['data'])
{
$id = $_GET['id'];
$data = $_GET['data'];
$key = $_GET['key'];
echo $id;
echo "<br>";
echo $data;
echo "<br>";
echo $key;
echo "<br>";
if(mysqli_query($connection, "update userbadges set level='$data' where id='$id'"));
echo 'success';
}
?>
Edit Connect.php
<?php
$connection = mysqli_connect('localhost', 'myusername', 'mypassword', 'leaderboard');
?>
You need to be checking everything to do with the mysqli_ calls
connect.php
<?php
$connection = mysqli_connect('localhost', 'myusername',
'mypassword', 'leaderboard');
if (!$connection) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
Your code:
<?php
include("../../config/connect.php");
if( isset($_GET['id'], $_GET['data'], $_GET['key']) ) {
$data = $_GET['data'];
$id = $_GET['id'];
$key = $_GET['key'];
echo $id;
echo "<br>";
echo $data;
echo "<br>";
echo $key;
echo "<br>";
$result = mysqli_query($connection,
"update userbadges set level='$data' where id='$id'");
if(! $result) {
echo mysqli_error($connections);
exit;
}
echo 'database update ' . mysqli_affected_rows($connection) . ' rows';
} else {
echo 'One of the required params is missing';
if ( $_GET ) {
print_r($_GET);
}
?>
Now if there is a problem like you forgot to change the mysql connection userid and password, or your hosting company use a seperate database server so localhost is not right, you will be told about the error.
Im running a Batch file as cronJob in my windows 7 machine,all I wanted is I want to create a log file ,when the cron Job is run along with the data,which it was displaying in the console.
The data ,is the echo statements which are present in the index.php which i have imported in the batch file.
Help me out to solve this issue.
index.php
<?php
echo "Welcome" ;
$fileD = "Login_".date('Y-m-d').".csv";
$fp1 = fopen($fileD, 'a+');
//Getting the files from below mentioned folder
$iterator1 = new FilesystemIterator("C:/wamp/www/logs1");
$iterator2 = new FilesystemIterator("C:/wamp/www/logs2");
$filelist = array();
foreach($iterator1 as $GLOBALS['entry1'])
{
if (strpos($entry1->getFilename(), "p1") === 0)
{
$filelist[] = $entry1->getFilename();
echo $entry1;
}
}
foreach($iterator2 as $GLOBALS['entry2']) {
if (strpos($entry2->getFilename(), "p2") === 0) {
$filelist[] = $entry2->getFilename();
echo "<br>";
echo $entry2;
}
}
$file1 = file_get_contents($entry1);
fwrite($fp1, $file1);
$file1 = file_get_contents($entry2);
fwrite($fp1, $file1);
fclose($fp1);
echo "<br/>";
echo "Done";
echo "<br/>";
//Deletes log file present in the logs folder
$n1= "$entry1";
if(!unlink($n1))
{
echo ("Error deleting file1 $n1");
}
else
{
echo ("Deleted $n1");
}
echo "<br/>";
$n2= "$entry2";
if(!unlink($n2))
{
echo ("Error deleting file2 $n2");
}
else
{
echo ("Deleted $n2");
}
echo "<br/>";
foreach (glob("*.csv") as $filename)
{
echo "$filename size " . filesize($filename) . "\n";
echo "<br>";
}
echo "<br>";
//$insertionDate = substr($filename,6,10);
$servername = "localhost";
$username = "user";
$password = "";
$dbname = "stat";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$file = file_get_contents($fileD);
$count = preg_match_all("/,Login,/", $file, $matches);
echo "Csv first word ";
$insertionDate = substr($file,1,10);
echo "<br/>";
echo "Total Hits:" . $totalLines = count(file($fileD));
echo "<br/>";
echo "Login:" . $count;
// Insert the Total hits and the corresponding success and failure count
$sql = "INSERT INTO hit_s (HitDate, count, category,success,failure,tcount,ocount)
VALUES ('$insertionDate', $totalLines, 'Hits',$success,$fail,$treeCnt,$oCnt)";
if ($conn->query($sql) === TRUE) {
echo "Total hits record inserted successfully \n";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$iterator = new FilesystemIterator("C:/wamp/www/Fed");
$filelist1 = array();
foreach($iterator as $GLOBALS['entry3'])
{
if (strpos($GLOBALS['entry3']->getFilename(), "*.csv") === 0)
{
$filelist1[] = $GLOBALS['entry3']->getFilename();
}
}
echo $GLOBALS['entry3'];
echo "<br/>";
$entry3="$fileD";
$n3= "$entry3";
if(!unlink($n3))
{
echo ("Error deleting $n3");
}
else
{
echo ("Deleted $n3");
}
echo "<br/>";
$conn->close();
?>
In batch file im calling the index.php file like below
C:\wamp\bin\php\php5.4.16\php.exe C:\wamp\www\Fed\csv\index.php
It looks like syslog will work for you:
$access = date("Y/m/d H:i:s");
syslog(LOG_WARNING, "Unauthorized client: $access {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']);
I am trying to make the different the different rows have line breaks but its not working.
How is this done!? Please check my code below
Thanks guys!
James
<?php
$conn = mysql_connect("", "", "");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
{
$search = "%" . $_POST["search"] . "%";
$searchterm = "%" . $_POST["searchterm"] . "%";
}
if (!mysql_select_db("")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT name,lastname,email
FROM test_mysql
WHERE name LIKE '$search%' AND lastname LIKE '$searchterm'";
$result = mysql_query($sql);
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["name"];
echo $row["lastname"];
echo $row["email"];
}
mysql_free_result($result);
?>
<?php echo $row["name"];?>
<br>
<?php echo $row["lastname"];?>
<br>
<?php echo $row["email"];?>
Beats me what you find so hard about it:
while ($row = mysql_fetch_array(...)) {
echo ...
echo '<br>';
}
I have written this PHP code and worked correctly... then I wanted a particular code segment to be worked as a function, but as soon I did this I didn't get the correct result... I'm confused what has gone wrong, can somebody please help me with this... Thanks a lot...
Here's the code gives me the error...
$arr1=array();
$date = date("D");
$link = mysql_connect ('localhost', 'root', '');
$db = mysql_select_db ('dayevent', $link);
function grabData($arr){ //works properly NOT as a function, but I want to make this code part act like a funciton
$i=0;
$sql = "SELECT event FROM events WHERE day = '$date'";
$sel = mysql_query($sql);
echo $sel; //this prints Resource id #3
if (mysql_num_rows($sel) > 0) { // but doesn't go into if block
while($row = mysql_fetch_array($sel)) {
echo $row['event'] . '<br />';
//storing DB query result in array
$arr[$i]=$row['event'];
$i=$i+1;
}
foreach($arr as $key => $value) {
echo $key . " " . $value . "<br />";
}
} else echo 'Nothing returned!'; //prints this instead of the correct result
}
grabData($arr1);
mysql_close();
Move this inside your function: $date = date("D");. The way it is now, $date is not defined. If you run with error_reporting(E_ALL) you would have caught it right away.
Test Below Code :
EDITED
$arr1=array();
$date = date("D");
$link = mysql_connect ('localhost', 'root', '');
$db = mysql_select_db ('dayevent', $link);
function grabData()
{
global $link,$date;
$arr = array();
$i=0;
$sql = "SELECT event FROM events WHERE day = '$date'";
$sel = mysql_query($sql,$link);
echo $sel; //this prints Resource id #3
if (mysql_num_rows($sel) > 0)
{
while($row = mysql_fetch_array($sel))
{
echo $row['event'] . '<br />';
$arr[$i]=$row['event'];
$i=$i+1;
}
foreach($arr as $key => $value)
{
echo $key . " " . $value . "<br>";
}
} else echo 'Nothing returned!'; //prints this instead of the correct result
return $arr;
}
print_r( grabData() );
mysql_close();