only displays a message in the conversation - php

i have make its here before. mySQL - how to show all records from the messages table, not just one
Hello
This is how I'm going to build a messaging system which make the user 1 and user 2 has a conversation somewhere.
That itself, I go to the site so come all the conversations appear on the page.
the problem is such that it does only one message from the database. Therefore, I would like it to display all messages from the database.
Database
CREATE TABLE IF NOT EXISTS `fms_opslagpm` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`fra_id` int(11) NOT NULL,
`til_id` int(11) NOT NULL,
`title` varchar(30) NOT NULL,
`besked` longtext NOT NULL,
`datotid` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `fms_opslagpm` (`id`, `fra_id`, `til_id`, `title`, `besked`, `datotid`) VALUES
(1, 2, 1, 'hrerherhe', 'hello world ', '2014-04-01 22:25:29'),
(2, 2, 1, 'hrerherhe', 'hej', '2014-04-01 23:51:49');
mysqli/php here.
$sql = "
SELECT fms_bruger.fornavn, fms_bruger.efternavn, fms_opslagpm.id, fms_opslagpm.fra_id, fms_opslagpm.til_id, fms_opslagpm.title, fms_opslagpm.besked
FROM fms_bruger INNER JOIN fms_opslagpm ON fms_bruger.id=fms_opslagpm.fra_id
WHERE fms_opslagpm.id = ? and fms_opslagpm.fra_id = ? OR fms_opslagpm.til_id = ?
GROUP BY fms_opslagpm.title ORDER BY fms_opslagpm.datotid DESC
";
if ($stmt = $this->mysqli->prepare($sql)) {
$stmt->bind_param('iii', $id, $fra_id, $til_id);
$id = $_GET["id"];
$fra_id = $_SESSION["id"];
$til_id = $_SESSION["id"];
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($fornavn, $efternavn, $id, $fra_id, $til_id, $title, $besked);
while ($stmt->fetch()) {
?>
<tr class="postbox">
<td class="beskedinfoBOX">
<p>
<?php
echo $fornavn . " " . $efternavn;
?>
</p>
</td>
<td>
<?php
//beskeden.
echo $besked;
?>
</td>
</tr>
<?php
}
$stmt->close();
}
else
{
echo 'Der opstod en fejl i erklæringen: ' . $this->mysqli->error;
}
This is how when I write fra_id = 2 and til_id = 1, then shows it is still only the content of the page. So samtidigvæk a message on the page.
fms_opslagpm = fra_id - is he / she who sends the message
fms_opslagpm = til_id - is he / she who receives the message

Your issue is that you are selecting only
WHERE fms_opslagpm.id = ?
So it will only return 1 row where there is an exact match on the id. It looks like you where trying to also select the rows that have the same title as the row with the id
GROUP BY fms_opslagpm.title
but even if you returned more than 1 row, this would have collapsed the results into 1 row again.
You need to change your query to get the title of the row WHERE fms_opslagpm.id = ?, and using OR select all the other rows with the same title.
Try -
SELECT
fms_bruger.fornavn,
fms_bruger.efternavn,
fms_opslagpm.id,
fms_opslagpm.title,
fms_opslagpm.besked
FROM fms_bruger
INNER JOIN fms_opslagpm ON fms_bruger.id=fms_opslagpm.fra_id
WHERE (
fms_opslagpm.id = ?
OR fms_opslagpm.title = (
SELECT fms_opslagpm.title
FROM fms_opslagpm
WHERE fms_opslagpm.id = ?
)
)
AND
(
fms_opslagpm.fra_id = ?
OR
fms_opslagpm.til_id = ?
)
ORDER BY fms_opslagpm.datotid DESC
See this SQLFiddle example - http://sqlfiddle.com/#!2/36d534/6
You will also need to include 1 more param to your bind_param
$stmt->bind_param('iiii', $id, $id1, $fra_id, $til_id);
$id = $_GET["id"];
$id1 = $_GET["id"];
$fra_id = $_SESSION["id"];
$til_id = $_SESSION["id"];

Related

stuck with multi-level categories and sub-categories php mysql

I do have a little directory listing products. Currently I can list Categories (level1) and sub-categories (level2).
I want to add potentially a 3rd level which would be sub-subcategories (level3).
Adding is working but listing (looping) does not work as it limits me to 2 levels.
I need some help to figure it out.
Here is the code for adding and listing and th mysql structure is:
CREATE TABLE `categories` (
`lcat_id` smallint(5) UNSIGNED NOT NULL,
`lcat_name` varchar(255) NOT NULL DEFAULT '',
`lcat_path` varchar(255) NOT NULL DEFAULT '',
`sub_cat` int(11) NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
My code is:
<?php
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>?action=newcat" method ="POST">
Category Name : <input type = "text" name = "cat_name" maxlength="250"><br><br>
Sub of category : <select name="lcat_id">
<option value=''>0</option>
<?php
$sql_cat = mysqli_query($db_connect,"SELECT * from ".TABLE_CATS." WHERE sub_cat='0' ORDER BY lcat_id") or die(mysqli_error($db_connect));
while($row_cat = mysqli_fetch_array($sql_cat)) {
extract($row_cat);
/*
$id = $row_cat["lcat_id"];
$name = $row_cat["lcat_name"];
$sub_cat = $row_cat["sub_cat"];
*/
echo "<option value='".$row_cat["lcat_id"]."'>".$row_cat['lcat_name']."</option>";
$sql_subcat = mysqli_query($db_connect,"SELECT * from ".TABLE_CATS." WHERE sub_cat='".$row_cat["lcat_id"]."' ") or die(mysqli_error($db_connect));
while($row_subcat = mysqli_fetch_array($sql_subcat)) {
extract($row_subcat);
/*
$id = $row_subcat["lcat_id"];
$namea = $row_subcat["lcat_name"];
$sub_cata = $row_subcat["sub_cat"];
*/
echo "<option value='".$row_subcat['lcat_id']."'>-> ".$row_subcat['lcat_name']."</option>";
}
}
?>
</select>
<input type = "submit" value = "New Category"><br>
</form>
<?php
if ($_GET['action']=="newcat"){
if ($_POST['cat_name']==""){
print "You did not put anything.<br/>Go back";
}
$sql_cat = mysqli_query($db_connect,"SELECT lcat_name from ".TABLE_CATS." WHERE lcat_name='".$_POST['cat_name']."' ") or die(mysqli_error($db_connect));
while($row_cat = mysqli_fetch_array($sql_cat)) {
extract($row_cat);
$name = $row_cat["lcat_name"];
}
if ($row_cat['cat_name']){
print "Category <b>".$_POST['cat_name']."</b> already exists in <b>".$mysql_db."</b>.<br>Please chose new name.<br/>Go back";
}
$sql_subcat = mysqli_query($db_connect,"SELECT * from ".TABLE_CATS." WHERE sub_cat='".$row_cat['lcat_id']."' AND lcat_name='".$row_cat["lcat_name"]."'") or die(mysqli_error($db_connect));
while($row_subcat = mysqli_fetch_array($sql_subcat)) {
extract($row_subcat);
$namea = $row_subcat["lcat_name"];
$sub_cat = $row_subcat["sub_cat"];
}
if ($row_subcat['lcat_name']) {
echo ("Sub-category <b>".$row_subcat['lcat_name']."</b> already exists in <b>$mysql_db</b>. Please chose new name.<br/>Go back");
exit;
} else {
$sql_query = "INSERT INTO ".TABLE_CATS." (lcat_name, lcat_path, sub_cat) VALUES ('".$_POST['cat_name']."','".$_POST['cat_name']."','".$_POST['lcat_id']."')";
$result = mysqli_query($db_connect,$sql_query);
echo "You added category :<b> ".$_POST['cat_name']."</b> in <b>$mysql_db</b><br/>Go back.";
}
}
?>
I would start by improving your categories table by -
adding the primary key
adding a foreign key constraint for parent_id
removing redundant path column
and removing the column name prefix (the table is already called categories)
CREATE TABLE `categories` (
`id` SMALLINT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
`parent_id` SMALLINT UNSIGNED,
CONSTRAINT `fk_parent_category` FOREIGN KEY (parent_id) REFERENCES categories (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Instead of having nested loops running queries to get child categories, or a recursive function, I would use a recursive Common Table Expression (CTE) to build and return the category hierarchy -
WITH RECURSIVE nested_cats AS (
SELECT *, 0 `depth`, CAST(`name` AS CHAR(200)) AS `path`
FROM `categories`
WHERE `parent_id` IS NULL
UNION ALL
SELECT `c`.*, `nc`.`depth` + 1, CONCAT(`nc`.`path`, ' > ', `c`.`name`)
FROM `categories` `c`
JOIN `nested_cats` `nc` ON `nc`.`id` = `c`.`parent_id`
)
SELECT * FROM `nested_cats` ORDER BY `path`;
In your current code you are building up your SQL by concatenating strings with user input without any validation. This makes your script rather vulnerable to SQL Injection. You should take some time to understand prepared statements and how they help you to protect against SQLi. You are currently using MySQLi which provides support for prepared statements and parameterization but for my example I am using PDO, as I find it more intuitive.
<?php
// During development, report all PHP errors
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$pdo = new PDO('mysql:dbname=test;host=localhost', 'db_user', 'db_pass');
$feedback = '';
$action = filter_input(INPUT_POST, 'action');
/* IF IS POST DO ADD */
if ($action == 'New Category'){
$cat_name = filter_input(INPUT_POST, 'cat_name', FILTER_SANITIZE_SPECIAL_CHARS);
if (empty($cat_name)){
$feedback = 'You did not put anything.';
} else {
$parent_id = filter_input(INPUT_POST, 'parent_id', FILTER_VALIDATE_INT, ['options' => ['default' => null]]);
// check to see if it already exists
$statement = $pdo->prepare('SELECT `name` FROM `categories` WHERE `name` = :name');
// execute the prepared statement
$statement->execute(['name' => $cat_name]);
// retrieve result rows
$rows = $statement->fetchAll(PDO::FETCH_OBJ);
if ($rows) {
$feedback = "Category {$rows[0]->name} already exists!";
} else {
$stmt = $pdo->prepare('INSERT INTO `categories` (`name`, `parent_id`) VALUES (:name, :parent_id)');
$stmt->execute([':name' => $cat_name, ':parent_id' => $parent_id]);
$feedback = "You added category: <b>{$cat_name}</b>.";
}
}
}
/* LOAD ALL CATEGORIES */
$sql = '
WITH RECURSIVE `nested_cats` AS (
SELECT *, 0 `depth`, CAST(`name` AS CHAR(200)) AS `path`
FROM `categories`
WHERE `parent_id` IS NULL
UNION ALL
SELECT c.*, `nc`.`depth` + 1, CONCAT(`nc`.`path`, " > ", `c`.`name`)
FROM `categories` `c`
JOIN `nested_cats` `nc` ON `nc`.`id` = `c`.`parent_id`
)
SELECT * FROM `nested_cats` ORDER BY `path`';
$result = $pdo->query($sql);
$categories = $result->fetchAll(PDO::FETCH_OBJ);
?>
<form action="" method ="POST">
Category Name : <input type="text" name="cat_name" maxlength="250"><br><br>
Sub of category : <select name="parent_id">
<option value=""> - </option>
<?php
foreach ($categories as $category) {
$indent = str_repeat('-> ', $category->depth);
echo "<option value='{$category->id}'>{$indent}{$category->name}</option>\r\n";
}
?>
</select>
<input type="submit" name="action" value="New Category"><br>
</form>
<div><?php echo $feedback; ?></div>
This is only a crude example and has no error checking/handling but it should get you moving in a better direction.

How do I change a value in a column in a table when I add another table?

How do I change the row value of a column in a table when I add another table?
How do you ask for help?
I have two tables in the database
The first table is called Drug
It consists of three columns:
Sample Table I
// TABLE Drug
DROP TABLE IF EXISTS `Drug`;
CREATE TABLE IF NOT EXISTS `Drug` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`brId` text NOT NULL,
`nameDrug` text NOT NULL,
PRIMARY KEY (`id`)
)
The second table is named brand
Sample Table II
// TABLE brand
DROP TABLE IF EXISTS `brand`;
CREATE TABLE IF NOT EXISTS `brand` (
`idBrand` int(11) NOT NULL AUTO_INCREMENT,
`brandName` text NOT NULL,
`theUse` text NOT NULL,
PRIMARY KEY (`idBrand`)
)
What I need is when you add a row in the brand table, brId is updated in the Drug table to the new idBrand by id in the drug table that was sent
I've done the following code because it does not work
<?php
require_once('include/config.php');
$id = $_POST['id'];
$brandName = $_POST['brandName'];
$theUse = $_POST['theUse'];
$query = "INSERT INTO brand
(brandName,theUse)VALUES('".$brandName."','".$theUse."');";
$insertBrand = mysqli_query($con,$query);
if($insertBrand)
{
$updatDrug = "UPDATE `drug` SET `brId` = new.idBrand WHERE `id` = '".$id."' ;";
$resultEnd = mysqli_query($con,$updatDrug);
if($resultEnd){
$result = 'OK';
echo json_encode($result);
}else{
$resultno = 'NO';
echo json_encode($resultno);
}
}
mysqli_close($con);
?>
After the INSERT, use mysqli_insert_id as the value for brId.
$br = mysqli_insert_id($con);
$updatDrug = "UPDATE drug SET brId = :brid WHERE id = :id";
$stmt = $con->prepare($updatDrug);
$stmt->bind_param('ii', $br, $id);
$stmt->execute();
$stmt->close();
And please avoid SQL INJECTION
Try transaction commit, here is an example
<?php
$db = new mysqli("localhost","root","","test"); //连接数据库
$db->autocommit(false); //设置为非自动提交——事务处理
$sql1 = "INSERT INTO `test`.`test1` (`name` )VALUES ('1' )";
$result1 = $db->query($sql1);
$sql2 = "INSERT INTO `test`.`test2` (`a` )VALUES ('1')";
$result2 = $db->query($sql2);
if ($result1 && $result2) {
$db->commit(); //全部成功,提交执行结果
echo '提交';
} else {
$db->rollback(); //有任何错误发生,回滚并取消执行结果
echo '回滚';
}
$db->autocommit(true);
$db->close();
?>

Nested FOREACH statements not working as I expected

In the first foreach statement, I have 4 attendeeid's in the attendees table.
In the second foreach, I have 1 attendeeid in the attend_date_temp table.
I'm trying to load a select box with names from the attendees table, less the one in the attend_date_temp table.
I thought that, since the first foreach would loop 4 times, the second foreach would also loop 4 times. But it doesn't. It loops one time, causing the code in the second foreach to not execute and load the select box with names.
How can this be written so that the second foreach loops 4 times like the first foreach so the select box will have the names loaded to it?
// Load Button Clicked
if(isset($_POST['loadnames'])) {
/* Read the history file and get the last record for each attendee for a particular group
and a particular member and write them to the attend_date_temp table if attend_date = CURDATE().*/
$stmt = $db->prepare('SELECT historyid, attend_date, attendeeid, groupid, memberid
FROM history
WHERE groupid = :groupid
AND memberid = :memberid
AND attend_date = CURDATE()
ORDER BY historyid
DESC LIMIT 1');
$stmt->bindValue(':groupid', $_POST['groupid'], PDO::PARAM_INT);
$stmt->bindValue(':memberid', $_SESSION['memberid'], PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row) {
$aid = $row[2]; // set the attendeeid
$stmt = $db->prepare('INSERT INTO attend_date_temp (attendeeid, groupid, memberid)
VALUES(:aid, :gid, :mid)');
$stmt->bindValue(':aid', $aid, PDO::PARAM_INT);
$stmt->bindValue(':gid', $_POST['groupid'], PDO::PARAM_INT);
$stmt->bindValue(':mid', $_SESSION['memberid'], PDO::PARAM_INT);
$stmt->execute();
}
$aaa = 0; // used to set the first select box entry to "Select"
/* Load the Select Box with names, less the ones found in attend_date_temp Table. */
$stmt = $db->prepare('SELECT a.attendeeid, fname, lname, a.groupid, a.memberid, s.attendeeid, suspend
FROM attendees AS a
JOIN suspended AS s ON a.attendeeid = s.attendeeid
WHERE a.memberid = :memberid
AND suspend = "N"
AND a.groupid = :groupid
ORDER BY lname');
$stmt->bindValue(':memberid', $_SESSION["memberid"], PDO::PARAM_INT);
$stmt->bindValue(':groupid', $_POST['groupid'], PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row){
echo '<script type="text/javascript">alert("In the first loop"); </script>';
$aid = $row[0];
$lname = $row[2];
$fname = $row[1];
$stmt = $db->prepare('SELECT attendeeid, memberid
FROM attend_date_temp
WHERE groupid = :groupid
AND attendeeid = :aid');
$stmt->bindValue(':groupid', $_POST['groupid'], PDO::PARAM_INT);
$stmt->bindValue(':aid', $aid, PDO::PARAM_INT);
$stmt->execute();
$result2 = $stmt->fetchAll();
foreach ($result2 as $row2) {
echo '<script type="text/javascript">alert("In the second loop"); </script>';
// evaluate attendees attendeeid against attend_date_temp attendeeid
if($row2['attendeeid'] != $aid){
// Load the flush Table with the IDs from the selected group
if($_SESSION['flush'] == 0) {
$stmt = $db->prepare('INSERT INTO flush (attendeeid, memberid)
VALUES(:attendeeid, :memberid)');
$stmt->bindValue(':attendeeid', $aid, PDO::PARAM_INT);
$stmt->bindValue(':memberid', $_SESSION['memberid'], PDO::PARAM_INT);
$stmt->execute();
}
if($aaa == 0) {
echo "<option value='Select'>Select</option>";
echo "<option value=".$aid.">".$lname.", ". $fname."</option>";
$aaa = 1;
} else {
echo "<option value=".$aid.">".$lname.", ". $fname."</option>";
}
}
}
}
$_SESSION['flush'] = 1;
exit();
} // last brace: loadnames
The attend_date_temp table:
DROP TABLE IF EXISTS `attend_date_temp`;
CREATE TABLE `attend_date_temp` (
`attendeeid` int(10) unsigned NOT NULL,
`groupid` int(10) unsigned NOT NULL,
`memberid` int(10) unsigned NOT NULL,
KEY `attendeeid` (`attendeeid`),
KEY `memberid` (`memberid`),
CONSTRAINT `attend_date_temp_ibfk_1` FOREIGN KEY (`attendeeid`) REFERENCES `attendees` (`attendeeid`) ON DELETE CASCADE,
CONSTRAINT `attend_date_temp_ibfk_2` FOREIGN KEY (`memberid`) REFERENCES `members` (`memberid`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The history table:
DROP TABLE IF EXISTS `history`;
CREATE TABLE `history` (
`historyid` int(10) unsigned NOT NULL AUTO_INCREMENT,
`amount` float NOT NULL,
`subsidy` char(1) NOT NULL,
`last_payment` date NOT NULL,
`amount_paid` float NOT NULL,
`balance` float NOT NULL,
`attend` char(1) NOT NULL DEFAULT 'N',
`attend_date` date NOT NULL,
`groupid` char(1) NOT NULL,
`attendeeid` int(10) unsigned NOT NULL,
`memberid` int(10) unsigned NOT NULL,
PRIMARY KEY (`historyid`),
KEY `attendeeid` (`attendeeid`),
CONSTRAINT `history_ibfk_15` FOREIGN KEY (`attendeeid`) REFERENCES `attendees` (`attendeeid`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
UPDATE:
This is a small part of a payment posting page. Names are loaded in the select box based on the group selected, then payments are posted by the name selected. This not only posts their payments but also their attendance. Once all the money has been collected, the remaining names not selected are marked as absent.
However, there are group members that attend groups that are not their own. When they make a payment, their money is posted and attendance recorded. BUT, and that's what this is all about, when that same person's group gets selected for payments, I don't want that person's name to get loaded. He's already paid, and his attendance has already been updated. To have him load again and be processed wld corrupt the history table. So I have to keep from double loading the same person. That's why I'm trying to use this attend_date_temp table.
Simple fix, use different variable names for the inner and outer loops:-
/* Load the Select Box with names, less the ones found in attend_date_temp Table. */
$stmt = $db->prepare('SELECT a.attendeeid, fname, lname, a.groupid, a.memberid, s.attendeeid, suspend
FROM attendees AS a
JOIN suspended AS s ON a.attendeeid = s.attendeeid
WHERE a.memberid = :memberid
AND suspend = "N"
AND a.groupid = :groupid
ORDER BY lname');
$stmt->bindValue(':memberid', $_SESSION["memberid"], PDO::PARAM_INT);
$stmt->bindValue(':groupid', $_POST['groupid'], PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row){
echo '<script type="text/javascript">alert("In the first loop"); </script>';
$aid = $row[0];
$lname = $row[2];
$fname = $row[1];
$stmt = $db->prepare('SELECT attendeeid, memberid
FROM attend_date_temp
WHERE groupid = :groupid
AND attendeeid = :aid');
$stmt->bindValue(':groupid', $_POST['groupid'], PDO::PARAM_INT);
$stmt->bindValue(':aid', $aid, PDO::PARAM_INT);
$stmt->execute();
$result2 = $stmt->fetchAll();
foreach ($result2 as $row2) {
echo '<script type="text/javascript">alert("In the second loop"); </script>';
// evaluate attendees attendeeid against attend_date_temp attendeeid
if($row2['attendeeid'] != $aid){
// Load the flush Table with the IDs from the selected group
if($_SESSION['flush'] == 0) {
$stmt = $db->prepare('INSERT INTO flush (attendeeid, memberid)
VALUES(:attendeeid, :memberid)');
$stmt->bindValue(':attendeeid', $aid, PDO::PARAM_INT);
$stmt->bindValue(':memberid', $_SESSION['memberid'], PDO::PARAM_INT);
$stmt->execute();
}
if($aaa == 0) {
echo "<option value='Select'>Select</option>";
echo "<option value=".$aid.">".$lname.", ". $fname."</option>";
$aaa = 1;
} else {
echo "<option value=".$aid.">".$lname.", ". $fname."</option>";
}
}
}
}
To do a join you would do something like this:-
$stmt = $db->prepare('SELECT a.attendeeid, fname, lname, a.groupid, a.memberid, s.attendeeid, suspend, adt.attendeeid AS adt_attendeeid, adt.memberid AS adt_memberid
FROM attendees AS a
INNER JOIN suspended AS s ON a.attendeeid = s.attendeeid
LEFT OUTER JOIN attend_date_temp adt ON adt.groupid = a.groupid AND adt.attendeeid = a.attendeeid
WHERE a.memberid = :memberid
AND suspend = "N"
AND a.groupid = :groupid
AND adt.groupid IS NULL
ORDER BY lname');
$stmt->bindValue(':memberid', $_SESSION["memberid"], PDO::PARAM_INT);
$stmt->bindValue(':groupid', $_POST['groupid'], PDO::PARAM_INT);
$stmt->execute();
EDIT
Think it can be more simply done like this (not tested so please excuse any typos)
<?php
$first = true;
/* Load the Select Box with names, less the ones found in attend_date_temp Table. */
$stmt = $db->prepare('SELECT a.attendeeid, fname, lname
FROM attendees AS a
INNER JOIN suspended AS s ON a.attendeeid = s.attendeeid
LEFT OUTER JOIN attend_date_temp adt ON adt.groupid = a.groupid AND adt.attendeeid = a.attendeeid
WHERE a.memberid = :memberid
AND suspend = "N"
AND a.groupid = :groupid
AND adt.groupid IS NULL
ORDER BY lname');
$stmt->bindValue(':memberid', $_SESSION["memberid"], PDO::PARAM_INT);
$stmt->bindValue(':groupid', $_POST['groupid'], PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row)
{
$aid = $row[0];
$lname = $row[2];
$fname = $row[1];
// Load the flush Table with the IDs from the selected group
if($_SESSION['flush'] == 0)
{
$stmt = $db->prepare('INSERT INTO flush (attendeeid, memberid)
VALUES(:attendeeid, :memberid)');
$stmt->bindValue(':attendeeid', $aid, PDO::PARAM_INT);
$stmt->bindValue(':memberid', $_SESSION['memberid'], PDO::PARAM_INT);
$stmt->execute();
}
if($first)
{
echo "<option value='Select'>Select</option>";
echo "<option value='".$aid."'>".$lname.", ". $fname."</option>";
$first = false;
}
else
{
echo "<option value='".$aid."'>".$lname.", ". $fname."</option>";
}
}

PHP PDO why select only first row in Database table?

I am PDO newbie, and i can't figure why i can select only first row in Table on database.
This is my DataBase TABLE :
Column Type Null Default Comments
id int(11) No
cred varchar(20) No
tok char(40) No
ptok char(40) No
t char(128) No
expires varchar(26) No
Indexes
Keyname Type Unique Packed Column Cardinality Collation Null Comment
PRIMARY BTREE Yes No id 1 A No
ptok BTREE Yes No ptok 1 A No
And this is my SELECT (find) function :
public function findTriplet($credential,$token, $persistentToken) {
$sql = "SELECT IF(SHA1(?) = {$this->tokenColumn}, 1, -1) AS token_match " .
"FROM {$this->tableName} WHERE {$this->credentialColumn} = ? " .
"AND {$this->persistentTokenColumn} = SHA1(?) LIMIT 1 ";
$query = $this->connection->prepare($sql);
$query->execute(array($token, $credential, $persistentToken));
$result = $query->fetchColumn();
if(!$result) {
return self::TRIPLET_NOT_FOUND;
}
elseif ($result == 1) {
return self::TRIPLET_FOUND;
}
else {
return self::TRIPLET_INVALID;
}
}
Anyway i tryed to search for answer , but i dont know PDO so good so its not matter..
I tryed play with that , no succses..
Anyone know what is my problem in the findTriplet function and what i am doing wrong ?
It will only select first database row so if i have more then 1 row's it will return false.
Thanks allot.
Remove "LIMIT 1" from your variable and see if results change:
$sql = "SELECT IF(SHA1(?) = {$this->tokenColumn}, 1, -1) AS token_match " .
"FROM {$this->tableName} WHERE {$this->credentialColumn} = ? " .
"AND {$this->persistentTokenColumn} = SHA1(?) LIMIT 1 ";
Becomes:
$sql = "SELECT IF(SHA1(?) = {$this->tokenColumn}, 1, -1) AS token_match " .
"FROM {$this->tableName} WHERE {$this->credentialColumn} = ? " .
"AND {$this->persistentTokenColumn} = SHA1(?)";
It appears you are retrieving a match, so you are seeing a SINGLE result. I'm not sure of the application, but you might want to keep a Limit in the SQL statement. Removing the LIMIT will at least be a good testing point.

PHP & MySQL array question

I'm trying to add the articles id to the title, summary and content but I don't know how to do it can some one help me solve this problem.
Here is the code that is giving me the problem.
while($row = mysqli_fetch_assoc($run)) {
$id[] = $row['id'];
$title[] = $row['id']['title'];
$summary[] = $row['id']['summary'];
$content[] = $row['id']['article_content'];
}
And here is my PHP and MySQL code in full below.
$x = 0;
$con = null;
$search = $_REQUEST['search'];
$id = array();
$title = array();
$summary = array();
$content = array();
$search_explode = mysqli_real_escape_string($dbc, $search);
$search_explode = explode(' ', $search_explode);
foreach($search_explode as $search_each) {
$x++;
if($x == 1){
$con .= " article_content LIKE '%$search_each%' OR title LIKE '%$search_each%' OR summary LIKE '%$search_each%'";
} else {
$con .= " OR article_content LIKE '%$search_each%' OR title LIKE '%$search_each%' OR summary LIKE '%$search_each%'";
}
}
$con = "SELECT users.*, users_articles.* FROM users_articles
INNER JOIN users ON users_articles.user_id = users.user_id
WHERE ($con)
AND users.active IS NULL
AND users.deletion = 0";
$run = mysqli_query($dbc, $con);
$search_term = mysqli_num_rows($run);
while($row = mysqli_fetch_assoc($run)) {
$id[] = $row['id'];
$title[] = $row['id']['title'];
$summary[] = $row['id']['summary'];
$content[] = $row['id']['article_content'];
}
while($row = mysqli_fetch_assoc($run)) {
// $id[] = $row['id']; you probably do not need this anymore
$title[$row['id']] = $row['title'];
$summary[$row['id']] = $row['summary'];
$content[$row['id']] = $row['article_content'];
}
// at this point, each array will contain rows
// with keys matching the corresponding id
var_dump($title);
var_dump($summary);
var_dump($content);
$title[] = $row['id']['title'];
$summary[] = $row['id']['summary'];
$content[] = $row['id']['article_content'];
mysqli_fetch_assoc will fetch an associated array. Accessing the data directly like so $row['summary'] should fix your problem.
EDIT
Are you talking about string concatenation?
$title[] = $row['id'] . ' ' . $row['title'];
$summary[] = $row['id'] . ' ' . $row['summary'];
$content[] = $row['id'] . ' ' . $row['article_content'];
The above code will basically append the title/summary/content to your article ID and add it into respective arrays.
I am not sure what you want to achieve but I would suggest the the following solution. Please take a look.
CREATE TABLE IF NOT EXISTS users (
user_id int(11) NOT NULL AUTO_INCREMENT,
name varchar(100) NOT NULL,
deletion int(11) NOT NULL DEFAULT '0',
active int(11) NOT NULL DEFAULT '1',
PRIMARY KEY (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table users
INSERT INTO users (user_id, name, deletion, active) VALUES
(1, 'John', 0, 1),
(2, 'George', 0, 1);
--
-- Table structure for table users_articles
CREATE TABLE IF NOT EXISTS users_articles (
id int(11) NOT NULL AUTO_INCREMENT,
user_id int(11) NOT NULL,
article_content varchar(255) NOT NULL,
title varchar(255) NOT NULL,
summary text NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
--
-- Dumping data for table users_articles
INSERT INTO users_articles (id, user_id, article_content, title, summary) VALUES
(1, 1, 'test', 'test', 'test test test test'),
(2, 2, 'test 2', 'test 2', 'test test'),
(3, 1, 'test 3', 'test 3 ', 'test test test test 3'),
(4, 2, 'test 3', 'test 3', 'test test 3');
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$mysqli = new mysqli("localhost", "root", "", "articles");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
/* Select queries return a resultset */
$con = 1;
$sql = "SELECT users.*, users_articles.* FROM users_articles
INNER JOIN users ON users_articles.user_id = users.user_id
WHERE ($con)
AND users.active = 1
AND users.deletion = 0";
$results = array();
if ($result = $mysqli->query($sql)) {
printf("Select returned %d rows.\n", $result->num_rows);
print '<pre>';
while ($row = $result->fetch_assoc()) {
$results[] = $row;
}
print_r($results);
print '</pre>';
/* free result set */
$result->close();
}
$mysqli->close();
?>
and when you will iterate $results you can concatenate id and other fields in that case you can utilize the result array in other areas too.

Categories