No output from PHP MySQL function array - php

I have an array with values declared in a while statement at the end of function fetch_conversation_messages in a backend file for a private message system. However, the array that is revealed is blank (other than the echos and print_rs that I have used for debugging).
I am very new to this forum, PHP and MySQL, so please help me.
Thank you in advance.
// Fetches all of the messages in the given converstion.
function fetch_conversation_messages($conversation_id){
$conversation_id = (int)$conversation_id;
$sql = "SELECT
`conversations_messages`.`message_date`,
`conversations_messages`.`message_text`,
`users`.`user_name`
FROM `conversations_messages`
INNER JOIN `users` ON `conversations_messages`.`user_id` = `users`.`user_id`
WHERE `conversations_messages`.`conversation_id` = {$conversation_id}
ORDER BY `conversations_messages`.`message_date` DESC";
$result = mysql_query($sql);
var_dump($result);
$messages = array();
while (($row = mysql_fetch_assoc($result)) !== false){
$messages[] = array(
'date' => $row['message_date'],
'unread' => $row['message_unread'],
'text' => $row['message_text'],
'user_name' => $row['user_name'],
);
echo mysql_num_rows($result);
var_dump($row);
}
echo count($messages);}
Also, there is a foreach error (written below as a comment on the first answer) in view_conversation.page.inc.php, which is this page:
<?php
$errors = array();
$valid_conversation = (isset($_GET['conversation_id']) && validate_conversation_id($_GET['conversation_id']));
if ($valid_conversation === false){
$errors[] = 'Invalid Conversation ID.';
}
if (isset($_POST['message'])){
if (empty($_POST['message'])){
$errors[] = 'You must enter a message.';
}
if (empty($errors)){
add_conversation_message($_GET['conversation_id'], $_POST['message']);
}
}
if (empty($errors) === false){
foreach ($errors as $error){
}
}
echo $error;
if ($valid_conversation){
/*if (isset($_POST['message'])){
update_conversation_last_view($_GET['conversation_id']);*/
$messages = fetch_conversation_messages($_GET['conversation_id']);
print_r($messages);
/*}else{
$messages = fetch_conversation_messages($_GET['conversation_id']);
update_conversation_last_view($_GET['conversation_id']);
}*/
}
?>
Inbox
Logout
<form action="" method="post">
<p><textarea name="message" rows="10" cols="110"></textarea></p>
<p><input type="submit" value="Add Message" /></p>
</form>
<?php
foreach ($messages as $message){
?>
<?php if ($message['unread']) echo 'unread'; ?>
<p class="name">Username: <?php echo $message['user_name']; ?></p>
<p class="text">Date: <?php echo date('d/m/Y H:i:s', $message['date']); ?></p>
<p>Message: <?php echo $message['text']; ?></p>
<?php
}
?>

Related

Unable to save submitted data in a MySQL database using PHP

Please may I ask for some assistance on this as I have been trying to fix for days now.It is accepting data when i key in but not appearing in the database when i check.
Here is my code
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST["btnSave"])) {
$db = new \dbPlayer\dbPlayer();
$msg = $db->open();
//echo '<script type="text/javascript"> alert("'.$msg.'");</script>';
if ($msg = "true") {
$userIds = $db->getAutoId("U");
$flup = new fileUploader\fileUploader();
$perPhoto = $flup->upload("/hms/files/photos/",$_FILES['perPhoto'], $userIds[1]);
// var_dump($perPhoto);
$handyCam=new \handyCam\handyCam();
if (strpos($perPhoto, 'Error:') === false) {
$dateNow=date("Y-m-d");
$data = array(
'userId' => $userIds[1],
'name' => $_POST['name'],
'studentId' => $_POST['studentId'],
'cellNo' => $_POST['cellNo'],
'gender' => $_POST['gender'],
'dob' => $handyCam->parseAppDate($_POST['dob']),
'passportNo' => $_POST['passportNo'],
'fatherName' => $_POST['fatherName'],
'fatherCellNo' => $_POST['fatherCellNo'],
'perPhoto' => $perPhoto,
'isActive' => 'Y'
);
$result = $db->insertData("studentinfo",$data);
if($result>=0) {
$id =intval($userIds[0])+1;
$query="UPDATE auto_id set number=".$id." where prefix='U';";
$result=$db->update($query)
Use this form to fix your problem
if(isset($_POST["btn-pub"]))
{
$title = $_POST["title"];
$cat = $_POST["postCat"];
$Author = "Imran AKKI";
$ImgName = $_FILES['PostImg']['name'];
$ImgTemp = $_FILES['PostImg']['tmp_name'];
$cont = $_POST["postCon"];
if (empty($title) || empty($cont)){
?>
<div class="alert alert-danger"><?php echo "Please fill in the fields"; ?>
</div>
<?php
}elseif($cont > 10000){
?>
<div class="alert alert-warning"><?php echo "The content of the post is very large"; ?>
</div>
<?php
}else{
$postImage = rand(0,10000)."_".$ImgName;
move_uploaded_file($ImgTemp,"Uploads\postImges\\" .$postImage);
$query = "INSERT INTO posts(PostTitle, PostCat, PostImg, PostContent,PostAuthor) VALUES ('$title','$cat','$postImage','$cont','$Author')";
$res=mysqli_query($conn,$query);
if(isset($res)){
?>
<div class="alert alert-success"><?php echo "The article was added successfully"; ?> </div>
<?php
}else{
?>
<div class="alert alert-danger"><?php echo "An error occurred during addition"; ?> </div>
<?php
}
}
}

White page PHP data insert

I am looking for answers on Stack Overflow and Google, have read about 50 same questions, every time its different, my head is already boiling. I have a simple PHP CRUD application with OOP.
It has a connection to the database (it works, my data is fetched from the database and I could see it at my index.php in Opera/Safari), has 'add' action (it doesn't work - white page), 'edit' action (it doesn't work - white page), 'delete' action (it works).
UPDATE2:
I have changed cli interpreter to 5.6. Now I see some errors (if I add this line to .ini file 'always_populate_raw_post_data' to '-1' errors are disappear, but I see a white page again):
Deprecated: Automatically populating $HTTP_RAW_POST_DATA is .
deprecated and will be removed in a future version. To avoid this
warning set 'always_populate_raw_post_data' to '-1' in php.ini and
use the php://input stream instead. in Unknown on line 0
Warning: Cannot modify header information - headers already sent in
Unknown on line 0
Array ( [type] => 2 [message] => Cannot modify header information -
headers already sent [file] => Unknown [line] => 0 ) Array ( [type]
=> 2 [message] => Cannot modify header information - headers already
sent [file] => Unknown [line] => 0 )
I am using in my project:
PHPSTORM
PHP CLI interpreter 7.2
PHP version 5.6
add.php code:
<html>
<head>
<title>Add Data</title>
</head>
<body>
<?php
include_once("classes/Crud.php");
include_once("classes/Validation.php");
$crud = new Crud();
$validation = new Validation();
if(isset($_POST['Submit'])) {
$name = $crud->escape_string($_POST['name']);
$age = $crud->escape_string($_POST['age']);
$email = $crud->escape_string($_POST['email']);
$msg = $validation->check_empty($_POST, array('name', 'age', 'email'));
$check_age = $validation->is_age_valid($_POST['age']);
$check_email = $validation->is_email_valid($_POST['email']);
if($msg != null) {
echo $msg;
echo "<br/><a href='javascript:self.history.back();'>Go Back</a>";
} elseif (!$check_age) {
echo 'Please provide proper age.';
} elseif (!$check_email) {
echo 'Please provide proper email.';
}
else {
$result = $crud->execute("INSERT INTO users(name,age,email) VALUES('$name','$age','$email')");
echo "<p style='color=green'>Data added successfully.";
echo "<br/><a href='index.php'>View Result</a>";
}
}?>
</body>
</html>
edit.php
<?php
include_once("classes/Crud.php");
$crud = new Crud();
$id = $crud->escape_string($_GET['id']);
$result = $crud->getData("SELECT * FROM users WHERE id=$id");
foreach ($result as $res) {
$name = $res['name'];
$age = $res['age'];
$email = $res['email'];
}
?>
<html>
<head>
<title>Edit Data</title>
</head>
<body>
Home
<br/><br/>
<form name="form1" method="post" action="editaction.php">
<table border="0">
<tr>
<td>Name</td>
<td><input type="text" name="name" value="<?php echo
$name;?>"></td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" name="age" value="<?php echo
$age;?>"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" value="<?php echo
$email;?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo
$_GET['id'];?>></td>
<td><input type="submit" name="update" value="Update">
</td>
</tr>
</table>
</form>
</body>
</html>
editaction.php
<?php
include_once("classes/Crud.php");
include_once("classes/Validation.php");
$crud = new Crud();
$validation = new Validation();
if(isset($_POST['update']))
{
$id = $crud->escape_string($_POST['id']);
$name = $crud->escape_string($_POST['name']);
$age = $crud->escape_string($_POST['age']);
$email = $crud->escape_string($_POST['email']);
$msg = $validation->check_empty($_POST, array('name', 'age', 'email'));
$check_age = $validation->is_age_valid($_POST['age']);
$check_email = $validation->is_email_valid($_POST['email']);
if($msg) {
echo $msg;
echo "<br/><a href='javascript:self.history.back();'>Go
Back</a>";
} elseif (!$check_age) {
echo 'Please provide proper age.';
} elseif (!$check_email) {
echo 'Please provide proper email.';
} else {
$result = $crud->execute("UPDATE users SET
name='$name',age='$age',email='$email' WHERE id=$id");
header("Location: index.php");
}
}
?>
DB SCHEME:
create database test;
use test;
CREATE TABLE `users` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(100) NOT NULL,
`age` int(3) NOT NULL,
`email` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
);
Crud.php
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
include_once 'DbConfig.php';
class Crud extends DbConfig
{
public function __construct()
{
parent::__construct();
}
public function getData($query)
{
$result = $this->connection->query($query);
if ($result == false) {
return false;
}
$rows = array();
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
public function execute($query)
{
$result = $this->connection->query($query);
if ($result == false) {
echo 'Error: cannot execute the command';
return false;
} else {
return true;
}
}
public function delete($id, $table)
{
$query = "DELETE FROM $table WHERE id = $id";
$result = $this->connection->query($query);
if ($result == false) {
echo 'Error: cannot delete id ' . $id . ' from table ' . $table;
return false;
} else {
return true;
}
}
public function escape_string($value)
{
return $this->connection->real_escape_string($value);
}
}
?>
The problem was with phpStorm. My app won't work with PHP interpreter running inside phpStorm.
I run my app in Apache2 HTTP server and it works well.

While trying to query a database, im getting back what I think is the table header names instead of the values

i am trying to write a simple chat script using php and mysql and i think i am returning the actual values of "Sender" and "Message" without ever getting the values of those columns. below is my index page where i am trying to display the queried results.
<?php
require('/includes/core.inc.php');
if (isset($_POST['send'])){
if(send_msg($_POST['sender'], $_POST['message'])){
echo "Message Sent";
}
else{
echo "message not sent";
}
}
?>
<div id ="messages">
<?php
$messages = get_msg();
$i = 0;
foreach($messages as $message){
$i = $i + 1;
echo '<strong>'.$message['sender'][$i].'Sent</strong><br/>';
echo $message['message'][$i].'<br /><br />';
}
?>
</div><!---Messages-->
<form action ="index.php" method="post">
<lable>Enter Name:<input type="text" name="sender"/></label>
<lable>Enter Message:<input type='text' name="message"></label>
<input type = "submit" name="send" value="send message">
</form>
and then here is my actual chat function. i know i am getting the values into and out of the database as i can check it through phpmyadmin but why isn't it displaying ont he page? thanks so much for any answer you may have for me ! sorry for bad english.
<?php
function get_msg(){
$query = "SELECT 'Sender', 'Message' FROM chat";
$run = mysql_query($query);
$messages = array();
while($message = mysql_fetch_assoc($run)){
$messages[] = array('sender'=>$message['Sender'],
'message'=>$message['Message']);
}
return $messages;
}
function send_msg($sender, $message){
if(!empty($sender) && !empty($message)){
$sender = mysql_real_escape_string($sender);
$message = mysql_real_escape_string($message);
$query = "INSERT INTO chat VALUES (null, '{$sender}','{$message}')";
if($run = mysql_query($query)){
return true;
}
else{
return false;
}
}
else{
return false;
}
}
?>
$query = "SELECT 'Sender', 'Message' FROM chat";
should be
$query = "SELECT Sender, Message FROM chat";
In the first case you select the fixed strings Sender and Message because single quotes.

How do i use php to be able to allow a user to view another users profile

i am creating a social network, when i first created my search bar for names i worked out well but when i click on any name it takes me to the profile of who ever is logged in here is my php code for my search bar
?php
include 'func.inc.php';
if (isset($_POST['full_name'])) {
$first_names = mysql_real_escape_string(htmlentities($_POST['full_name']));
$errors = array();
if (empty($first_names)) {
$errors[] = 'Please enter a search term';
} else if (strlen($first_names)<3) {
$errors[] = 'Your search term must be three or more charecters';
} else if (search_results($first_names) === false) {
$errors[] = 'Your search for '.$first_names.' returned no results';
}
?>
<?php
if (empty($errors)) {
$results = search_results($first_names);
$results_num = count($results);
echo '<div align="center"> <p>Your search for <strong>', $first_names, '</strong> returned <strong>', $results_num, '</strong> results</p> </div>';
foreach($results as $result) {
echo '<h3> <strong> <div align="center"> ', $result['first_name'],' ', $result['last_name'], '<br> ', $result['address'],'</div> </strong> </h3>';
}
}
}
?>
here is func.inc.php
<?php
include 'db.inc.php';
function search_results($first_names) {
$returned_results = array();
$where = "";
$first_names = preg_split('/[\s]+/', $first_names);
$total_first_names = count($first_names);
foreach($first_names as $key=>$first_name) {
$where .= "`full_name` LIKE '%$first_name%'";
if ($first_name != ($total_first_names - 1)) {
$where .= " AND ";
}
}
$results = "SELECT `user_id`, `first_name`, `last_name` FROM `users` WHERE $where";
$results_num = ($results = mysql_query($results)) ? mysql_num_rows($results) : 0;
if ($results_num === 0) {
return false;
} else {
while ($results_row = mysql_fetch_assoc($results)) {
$returned_results[] = array(
'first_name' => $results_row['first_name'],
'last_name' => $results_row['last_name'],
'user_id' => $results_row['user_id']\
);
}
return $returned_results;
}
}
?>
and please explain it in detail im not that good with this email me if anything at philipnagel511#gmail.com

PHP MySQL not inserting into database

I have heard of this issue but can't seem to figure it out. I have the database and table names correct. I am not finding any errors and i even inserted a table myself on phpmyadmin that worked but when I tried to do it on my site it doesnt work. I even tested the connection..Not sure what to do now
Maybe someone can take a look at my code and see if they notice anything
<?php
if(mysql_connect('<db>', '<un>', '<pw>') && mysql_select_db('smiles'))
{
$time = time();
$errors = array();
if(isset($_POST['guestbook_name'], $_POST['guestbook_message'])){
$guestbook_name = mysql_real_escape_string(htmlentities($_POST['guestbook_name']));
$guestbook_message = mysql_real_escape_string(htmlentities($_POST['guestbook_message']));
if (empty($guestbook_name) || empty($guestbook_message)) {
$errors[] = 'All Fields are required.';
}
if (strlen($guestbook_name)>25 || strlen($guestbook_message)>255) {
$errors[] = 'One or more fields exceed the character limit.';
}
if (empty($errors)) {
$insert = "INSERT INTO 'guestbook'VALUES('','$time','$guestbook_name','$guestbook_message')";
if($insert = mysql_query($insert)){
header('Location: '.$_SERVER['PHP_SELF']);
} else{
$errors[] = 'Something went wrong . Please try again.';
}
} else {
foreach($errors as $error) {
echo '<p>'.$error.'</p>';
}
}
}
//display entries
}
else {
'Fixing idiot';
}
?>
<hr />
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']);?>" method="POST">
<p>Post Somethign</p>
<br />
Name:<br /><input type="text" name="guestbook_name" maxlength="25" />
<br />
Message:
<br />
<textarea name="guestbook_message" rows="6" coles="30"maxlength="255"></textarea>
<input type="submit" value="Post" />
</form>
Remove quotes from table name 'guestbook' and leave a space between it and values
Table name doesn't need quotes and supossing you're using id autoincrement, don't insert an empty string. So it should be:
$insert = "INSERT INTO guestbook VALUES('$time','$guestbook_name','$guestbook_message')";
Also, take a look at your $time value. What MySQL data type is?
After the insert, try to display the mysql error:
$conn = mysql_connect('<db>', '<un>', '<pw>');
mysql_query($insert)
if (mysql_errno($conn)){
$errors[] = mysql_error($conn);
}else{
header('Location: '.$_SERVER['PHP_SELF']);
}
EDIT: The hole snippet should be similar to:
<?php
$conn = mysql_connect('<db>', '<un>', '<pw>')
if( $conn && mysql_select_db('smiles')) //Note $conn
{
$time = time();
$errors = array();
if(isset($_POST['guestbook_name'], $_POST['guestbook_message'])){
$guestbook_name = mysql_real_escape_string(htmlentities($_POST['guestbook_name']));
$guestbook_message = mysql_real_escape_string(htmlentities($_POST['guestbook_message']));
if (empty($guestbook_name) || empty($guestbook_message)) {
$errors[] = 'All Fields are required.';
}
if (strlen($guestbook_name)>25 || strlen($guestbook_message)>255) {
$errors[] = 'One or more fields exceed the character limit.';
}
if (empty($errors)) {
mysql_query($insert)
$insert = "INSERT INTO guestbook VALUES('$time','$guestbook_name','$guestbook_message')";
if (mysql_errno($conn)){
$errors[] = mysql_error($conn);
}else{
header('Location: '.$_SERVER['PHP_SELF']);
}
} else {
foreach($errors as $error) {
echo '<p>'.$error.'</p>';
}
}
}
//display entries
}
you can try below query for insertion:
$insert = "INSERT INTO guestbook VALUES('','{$time}','{$guestbook_name}','{$guestbook_message}')";

Categories