what is this. can't do this again and again and again.. lol
if (!isset($_GET['hash'])) {
//we give the value of the starting row to 0 because nothing was found in URL
$hash = 'Teen' . ' ' . chr(38) . ' ' . 'Young Adult';
//otherwise we take the value from the URL
} else {
//if (strpos($_GET['hash'], '&') !== false) {
$regex = "~[ ]\K&~";
$hash = preg_replace($regex, chr(38), $_GET['hash']);
//$hash = preg_replace('/&/', chr(38) ,$_GET['hash']);
//$hash = str_replace("&", chr(38), $_GET['hash']);
echo $hash;
//$hash =
//}
}
//// --- etc etc
$DBH = new PDO($hostDb, $user, $password);
$WTH = $DBH -> prepare( "SELECT asin FROM asin WHERE active=1 AND node = :hash LIMIT $startrow, 10" );
$WTH->bindParam(':hash', $hash, PDO::PARAM_STR);
$WTH->setFetchMode(PDO::FETCH_ASSOC);
$WTH -> execute();
foreach($wea as $item)
{
echo '<td>';
echo '' . $item["node"] . '';
echo '</td>';
echo '<td>';
echo $item["c"];
echo '</td>';
echo '</tr>';
}
echo '</td></tr></table>';
echo '</td></tr></table>';
If this is run, the echo says Only Teen??? and not Teen & Young Adult? Help? Obviously mysql will not take &. Any solutions?
Related
I have this code and in "SELECT * FROM Blogi WHERE PostID=".
How to get each line separately so that takes postedBY, title, date, content by PostID
<?php
try{
$Blog = $conn->prepare("SELECT * FROM Blogi WHERE PostID=");
$Blog->execute();
}catch(PDOException $e){
echo $e->getMessage();
}
$fetch = $Blog->fetchAll();
$usercount = $Blog->rowCount();
if($usercount > 0){
foreach($fetch as $f){
$PostID = $f['PostID'];
$PostedBY = $f['PostedBY'];
$Title = $f['Title'];
$Date = $f['Date'];
$Content = $f['Content'];
}
}else{
session_destroy();
header('location: index.php');
}
?>
I have very bad English, so I don't know anyone can understand this.
How to do it further this postID="" to that he would start to work?
You have already done it in foreach loop... so add a line for output like... Also you aren't sending any PostID value to your query, be sure that you are sending a value for it.
foreach($fetch as $f){
$PostID = $f['PostID'];
$PostedBY = $f['PostedBY']
$Title = $f['Title'];
$Date = $f['Date'];
$Content = $f['Content'];
echo $PostID . " " . $Title . " " . $Date . " " . $Content . "<br />";
}
I'm trying to implement memcached into my server due to how large the database gets so quickly. I was wondering how I'm able to implement it into this code:
function getWorkers($db)
{
$meminstance = new Memcache();
$meminstance->pconnect('localhost', 11211);
$del = $db->prepare('SELECT DISTINCT(address) from works');
$del->execute();
$arr = $del->fetchAll();
$works = getMaxWork($db);
foreach($arr as $a)
{
$del = $db->prepare('SELECT * FROM works WHERE address = \'' . $a[0] . '\'');
$del->execute();
$work = $del->rowCount();
echo '<tr>';
echo '<td>' . htmlspecialchars($a[0], ENT_QUOTES, 'UTF-8') . '</td>';
echo '<td>' . $work . '</td>';
echo '<td>' . round(intval($work)/intval($works)*100, 2) . '</td>';
echo '</tr>';
}
}
Here you go
function getData($db)
{
$meminstance = new Memcache();
$meminstance->pconnect('localhost', 11211);
$sqlQuery = 'SELECT DISTINCT(address) from works';
$memcacheKey = md5($sqlQuery);
if ( $arr = $meminstance->get(memcacheKey) )
{
// its in cache do nothing
}
else
{
// its not in cache, so we came here, lets now get it from db and cache it
$del = $db->prepare($sqlQuery);
$del->execute();
$arr = $del->fetchAll();
$works = getMaxWork($db);
// lets now cache it
$meminstance->set(memcacheKey,$arr);
}
foreach($arr as $a)
{
$sqlQuery = 'SELECT * FROM works WHERE address = \'' . $a[0] . '\'';
$memcacheKey = md5($sqlQuery);
if ( $del = $meminstance->get($memcacheKey))
{
//its in cache yaaaaaaaa :D
}
else
{
$del = $db->prepare('SELECT * FROM works WHERE address = \'' . $a[0] . '\'');
$del->execute();
$work = $del->rowCount();
// lets cache it here
$meminstance->set($memcacheKey,$del);
}
echo '<tr>';
echo '<td>' . htmlspecialchars($a[0], ENT_QUOTES, 'UTF-8') . '</td>';
echo '<td>' . $work . '</td>';
echo '<td>' . round(intval($work)/intval($works)*100, 2) . '</td>';
echo '</tr>';
}
}
The logic when you are using memcache in your website. Is it md5 the sql queries so they will be unique. You first try to fetch from memcached, ( you md5 the sql Query) so it will be the key. if you dont get anything, you get the data from database and then save it into memcache. Which means you md5 the sql Query to make they key so it will be unique, and you pass the returned result from database as its value
key ===> md5(Sql Query )
value ==> the object, result set that is fetched from database
// pseudocode
if ( Get data from memcache passed )
{
return result;
}
else
{
get the data from database
save it into memcache
}
Note: If you are running on a single server, better to look into APC rather than memcached
I need to migrate data within our old bug tracker (Zentrack) to our new one and the only import method I can use is to import from CSV. To do so I need the data from two tables, tickets and logs so I wrote the script below in php.
<?php
error_reporting(E_ALL);
$host = "localhost";
$user = "dbuser";
$pass = "dbpass";
$db = "zentrk";
$users[1] = 'john';
$users[4] = 'sally';
$users[5] = 'nick';
$users[6] = 'ralph';
$r = mysql_connect($host, $user, $pass);
if (!$r) {
echo "Could not connect to server\n";
trigger_error(mysql_error(), E_USER_ERROR);
}
echo mysql_get_server_info() . "\n";
$r2 = mysql_select_db($db);
if (!$r2) {
echo "Cannot select database\n";
trigger_error(mysql_error(), E_USER_ERROR);
}
$query_tickets = "select ZENTRACK_TICKETS.id, ZENTRACK_TICKETS.title, ZENTRACK_TICKETS.priority, ZENTRACK_TICKETS.status, ZENTRACK_TICKETS.description, ZENTRACK_TICKETS.otime,
ZENTRACK_TICKETS.type_id, ZENTRACK_TICKETS.user_id, ZENTRACK_TICKETS.system_id, ZENTRACK_TICKETS.creator_id, ZENTRACK_TICKETS.proj_key
from ZENTRACK_TICKETS
where ZENTRACK_TICKETS.status = 'OPEN'
and ZENTRACK_TICKETS.system_id in ('18', '3', '6', '1', '16', '7', '9', '4', '20')
and ZENTRACK_TICKETS.type_id not in ('1', '10', '5')";
$rs = mysql_query($query_tickets);
if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Query: $query executed\n";
}
$export = array();
$export[] = 'id,title,created date,priority,type,assigned,description,system,creator,project key,log1,log2,log3,log4,log5,log6,log7,log8,log9,log10
';
while ($row = mysql_fetch_assoc($rs)) {
$line = '';
$count = 0;
$line .= $row['id'] . "," . $row['title'] . "," . date('d-M-y h:m a',$row['otime']) . "," . $row['priority'] . "," . $row['type_id'] . "," . $row['user_id'] . "," . $row['description'] . "," . $row['system_id'] . "," . $row['creator_id'] . "," . $row['proj_key'] . ",";
$logs = find_logs($id = $row['id']);
foreach($logs as $log_entry) {
$line .= $log_entry.",";
$count++;
}
while($count < 10) {
$line .= ",";
$count++;
}
$export[] = $line.'
';
}
mysql_close();
// print_r($export);
$file = 'tickets.csv';
file_put_contents($file, $export);
function find_logs($ticket) {
$content = array();
$query = "select ZENTRACK_LOGS.created, ZENTRACK_LOGS.user_id, ZENTRACK_LOGS.entry
from ZENTRACK_LOGS
where ZENTRACK_LOGS.ticket_id = $ticket
and ZENTRACK_LOGS.action <> 'EDIT' ";
$rs = mysql_query($query);
if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysql_error(), E_USER_ERROR);
}
while ($row = mysql_fetch_assoc($rs)) {
$date = date('d-M-y h:m a',$row['created']);
$content[] = $date . ";" . $row['user_id'] . ";" . $row['entry'];
}
return $content;
}
?>
I'm running into two problems with this script, that I'm sure are due to me being new to PHP.
1) I need to escape out the data in $row['description'] as it contains both carriage returns and , in the text that is incorrectly breaking the output into new rows when saved to CSV. I need to save the contents of this row within " " but I'm not sure how to do so.
2) The data returned in $row['user_id'], $row['creator_id'] and $row['user_id'] within the find_logs function returns a number, which I need to find that number and replace with the corresponding string in the $users array. What's the best way to do this?
When dealing with csv files use fgetcsv and fputcsv, provide it with an array and it will handle the escaping for you.
I have a simple program that I am trying to implement some sort of pagination/capability to navigate through individual records in a MySQL database. The code itself calls a function that returns an associative array so that the records may be navigated sequentially in the case of non-sequential indices being made by deletes.
function getKeys($handle, $user, $password) {
try {
$conn = new PDO($handle,$user,$password);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Error connectiong to database. Error: (" . $e -> getMessage() . ")";
}
$sql = "Select Workstation_ID from Workstation";
$result = $conn -> query($sql);
$resultArray = array();
while ( $row = $result -> fetch()) {
$resultArray[] = $row;
}
$conn = null;
return $resultArray; }
I am attempting to store the result from this function into a variable and from there try to increment that variable for use in an other function:
$Keys = getKeys($dsn,$un,$pw);
$i = 0;
$currID = $Keys[$i][0];
$row = getResultSet($dsn,$un,$pw,$currID);
I would then use the $row to display the current workstation :
echo "<hr class='viewHR'>";
echo "</br></br><div class='viewFormat'>";
echo "<form name = 'updateWorkstationForm' action ='updateWorkstation.php' method ='post'>";
echo "<b>Workstation Name:</b><br><input type = 'Textbox' name = 'pcName' value = '" . $row['Workstation_Name'] . "'/></br>";
echo "<b>Serial Number: </b><br> <input type = 'Textbox' name = 'SN' value = '" . $row['Serial_Number'] . "'/></br>";
echo "<b>Model</b></br>";
echo "<select name ='modelSelect'>";
echo "<option value = '".$row['Model_ID'] . "'>" . $row['Model'] . "</option>";
echo "</select></br>";
echo "<b>Department</b></br>";
echo "<select name ='DepartmentSelect'>";
echo "<option value = '".$row['Department_ID'] . "'>" . $row['Department'] . " </option>";
echo "</select></br>";
I was wondering if I was going about this completely wrong or how I would approach incrementing the array's index to display each record on a click of an anchor tag or button the whole file is as follows :
<html>
<body>
<div>
<?php
$un = "xxx";
$pw = "xxxxxx";
$dsn = "mysql:host=127.0.0.1;dbname=xxxxxxxxxxx";
$Keys = getKeys($dsn,$un,$pw);
$i = 0;
$currID = $Keys[$i][0];
$row = getResultSet($dsn,$un,$pw,$currID);
echo "<hr class='viewHR'>";
echo "</br></br><div class='viewFormat'>";
echo "<form name = 'updateWorkstationForm' action ='updateWorkstation.php' method = 'post'>";
echo "<b>Workstation Name:</b><br> <input type = 'Textbox' name = 'pcName' value = '" . $row['Workstation_Name'] . "'/></br>";
echo "<b>Serial Number: </b><br> <input type = 'Textbox' name = 'SN' value = '" . $row['Serial_Number'] . "'/></br>";
echo "<b>Model</b></br>";
echo "<select name ='modelSelect'>";
echo "<option value = '".$row['Model_ID'] . "'>" . $row['Model'] . "</option>";
echo "</select></br>";
echo "<b>Department</b></br>";
echo "<select name ='DepartmentSelect'>";
echo "<option value = '".$row['Department_ID'] . "'>" . $row['Department'] . "</option>";
echo "</select></br>";
echo "<b>Room</b></br>";
echo "<select name ='RoomSelect'>";
echo "<option value = '".$row['Room_ID'] . "'>" . $row['Room'] . "</option>";
echo "</select></br>";
echo "<b>Property Status</b> </br>";
echo "<select name = 'propertyStatus'>";
echo "<option value = '".$row['Property_Status_ID'] . "'>" . $row['Property_Status'] . "</option>";
echo "</select></br>";
if ($row['Property_Status'] != "Owned"){
echo "<b>Lease Company:</b> ";
echo "<select name = leaseSelect>";
echo "<option value = '" . $row['Lease_Info_ID'] ."'>Company:" . $row['Company'] . ", Start: " . $row['Start_Date'] . "End: " .$row['End_Date'] . "</option>";
echo "</select></br>";
}
echo "<b>Cart</b></br>";
echo "<select name ='cartSelect'>";
echo "<option value = '".$row['Cart_ID'] . "'>" . $row['Cart_Type'] . "</option>";
echo "</select></br>";
echo "<b>Workstation Comments: </b><br> <Textarea rows='5' cols='60' name = 'wsComments'> ". $row['Workstation_Comment'] . " </Textarea></br>";
echo "<b>Location Comments: </b><br> <Textarea rows='5' cols='60' name = 'locComments'> ". $row['Workstation_Comment'] . " </Textarea></br>";
echo "<input type = 'submit' value = 'Update' />";
echo "<input type = 'button' value = 'Cancel' onclick = 'location.reload(this);' />";
echo "</form>";
echo "</div>";
/*Function to return a parallel array. This is so that non-sequential records in the database may be described sequentially with the help of an array's indices*/
function getKeys($handle, $user, $password) {
try {
$conn = new PDO($handle,$user,$password);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Error connectiong to database. Error: (" . $e -> getMessage() . ")";
}
$sql = "Select Workstation_ID from Workstation";
$result = $conn -> query($sql);
$resultArray = array();
while ( $row = $result -> fetch()) {
$resultArray[] = $row;
}
$conn = null;
return $resultArray;
}
function getResultSet($handle, $user, $password, $ID) {
$resultSet = "";
try {
$conn = new PDO($handle,$user,$password);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Error connectiong to database. Error: (" . $e -> getMessage() . ")";
}
$sql = "Select Workstation.Workstation_ID,Workstation.Model_ID,Workstation.Property_Status_ID,workstation.Lease_Info_ID, Workstation.Workstation_Name, Workstation.Serial_Number, Model.Model, Department.Department,Room.Room,Property_Status.Property_Status,Lease_Info.Start_Date,Lease_Info.End_Date,Lease_Info.Company,Lease_Info.Lease_Comment,Cart.Cart_Type,Workstation.Workstation_Comment,Workstation.Location_Comment from Workstation INNER JOIN Model ON Workstation.Model_ID = Model.Model_ID INNER JOIN Department ON Workstation.Department_ID = Department.Department_ID INNER JOIN Room ON Workstation.Room_ID = Room.Room_ID INNER JOIN Property_Status ON Workstation.Property_Status_ID = Property_Status.Property_Status_ID INNER JOIN Lease_Info ON Workstation.Lease_Info_ID = Lease_Info.Lease_Info_ID INNER JOIN Cart ON Workstation.Cart_ID = Cart.Cart_ID where Workstation_ID = :ID";
$pstmt = $conn -> prepare($sql);
if(!$pstmt) {
echo "Error preparing the statement. Error: (" . $conn -> ErrorInfo() . ")";
}
$pstmt -> bindParam(':ID', $ID);
try {
$pstmt -> execute();
}
catch(PDOException $e) {
echo "Failed to execute prepared Statement. Error: (" . $e -> getmessage() . ")";
}
$resultSet = $pstmt -> fetch();
return $resultSet;
$conn = null;
}
?>
</div>
</body>
</html>
Any criticism, insight, or pointers would be greatly appreciated.
You shouldn’t be fetching all records if you only intend to display a subset, or just one.
To paginate, use the LIMIT clause. So, if you split records into pages of ten, then to get the first page your query would be:
SELECT * FROM workstations LIMIT 0,10
Where the first number is the offset, and the second number is the number of records after the offset you wish to fetch. To fetch the second page, you’d change the limit clause to be LIMIT 10,10; to fetch the third page LIMIT 20,10, and so on. The PHP equation is:
$offset = (($page - 1) * $records_per_page);
The page value can come from a $_GET variable, like http://www.example.com/?page=1.
Secondly, if you’re only wanting to display one record, then fetch that one:
SELECT * FROM workstations WHERE id = ? LIMIT 1
Pass the ID via a $_GET parameter again, and use PDO to bind it to avoid SQL injection vulnerabilities:
<?php
$sql = "SELECT * FROM workstations WHERE id = :id LIMIT 1";
$sth = $db->prepare($sql);
$sth->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
$sth->execute();
$row = $sth->fetchObject();
I am retrieving 3 fields from a database, and by default, only the username field will have content. The other information will be added in from a user application. I want to show the field as "No Info" if there is no entry in the field. I am trying to use both empty() and is_null() to no avail. A var_dump of $row['firstname'] and $row['lastname'] returns NULL in both cases.
<?php
if (isset($_GET["subcat"]))
$subcat = $_GET["subcat"];
if (isset($_GET["searchstring"])) {
$searchstring = $_GET["searchstring"];
}
$con = mysqli_connect("localhost","user","password", "database");
if (!$con) {
echo "Can't connect to MySQL Server. Errorcode: %s\n". mysqli_connect_error();
exit;
}
$table = 'USERS';
$brand = '%' . $searchstring . '%';
$rows = getRowsByArticleSearch($brand, $table);
echo "<table border='0' width='100%'><tr>" . "\n";
echo "<td width='15%'>Username</td>" . "\n";
echo "<td width='15%'>Firstname</td>" . "\n";
echo "<td width='15%'>Surname</td>" . "\n";
echo "</tr>\n";
foreach ($rows as $row) {
if (is_null($row['firstname']) || $row['firstname'] == "") {
$row['firstname'] == "No Info";
}
if ($row['lastname'] == null || $row['lastname'] == "") {
$row['firstname'] == "No Info";
}
var_dump($row['firstname']);
var_dump($row['lastname']);
echo '<tr>' . "\n";
echo '<td>'.$row['username'].'</td>' . "\n";
echo '<td>'.$row['firstname'].'</td>' . "\n";
echo '<td>'.$row['lastname'].'</td>' . "\n";
echo '</tr>' . "\n";
}
echo "</table>\n";
function getRowsByArticleSearch($searchString, $table) {
$con = mysqli_connect("localhost","user","password", "database");
$recordsQuery = "SELECT username, firstname, lastname FROM $table WHERE lower(username) LIKE ? ";
if ($getRecords = $con->prepare($recordsQuery)) {
$getRecords->bind_param("s", $searchString);
$getRecords->execute();
$getRecords->bind_result($username, $firstname, $lastname);
$rows = array();
while ($getRecords->fetch()) {
$row = array(
'username' => $username,
'firstname' => $firstname,
'lastname' => $lastname,
);
$rows[] = $row;
}
return $rows;
} else {
print_r($con->error);
}
}
Turn on display_errors and set error_reporting to E_ALL (either in php.ini or in a htaccess). This should reveal any non-obvious mistakes.
Try the following for checking if something is empty:
<?php
if(!isset($row['...']) || empty($row['...']))
{
$row['firstname'] = 'No Info';
}
?>
Also, please note you're using '==' to set the $row things to 'No Info'. Al this does is return 'true' (or 1). Use a single '=' to set variables.
First and your main issue:
You are using comparison operators in $row['firstname'] == "No Info"; instead of assignement operators $row['firstname'] = "No Info";
Other issues:
Why do you establish the connection twice? Or actually multiple times? Find a way to let your functions know the connection!
Factor the connection out into an include.
Why do you do that while loop, if you can access the returned array directly?
Two things to try...
if($row['field'] === NULL) { }
if(isset($row['field'])) { }
You can check the empty data using is_null property .Refer this link for more details
http://php.net/manual/en/function.is-null.php
is_null($row['field'])
Use
if(is_null($rows['field'])){
// Code Here
}else{
//code here
}