Chat system foreach dynamic - php

What I'm trying to do is a User -> Admin || Admin -> User) chat system. What I've come up with so far looks really messed up, I tried JOIN on the select via SQLfiddle and it didn't work out so good.
Hopefully someone has a better idea and knows how to solve this problem.
My live chat PHP code -> http://pastebin.com/6z9ajCMW
And for my database structure for the live_chat and live_chat_admin it's here -> http://sqlfiddle.com/#!2/ae70ec/26
And to get a basic idea of what I'm trying to make.

Maybe you should try to create a unique id for each chat so it easier for you to retrive it. Tables will be similar to something like this.
Everytime a user starts a new chat, a new row is inserted in chat_unique. This will prevent other users to join a chat.
However, your page will reload everytime someone sends a new message. The best way would be to use Ajax.

Here you go
You just need to align right and left accordingly to the admin and the user that you have in your form as i have like in the below code
i.e.,
echo '<div align="right">';
and ending with
echo '</div>';
Code :
<?php
echo '<div class="live_chat">';
$user = 'root';
$pass = '';
// admin chat
$conn = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->prepare("SELECT * FROM live_chat_admin WHERE receiver = :user_id");
$sth->bindValue(':user_id', '2', PDO::PARAM_INT);
$sth->execute();
foreach ($sth as $row) {
// Test message #1
echo '<div align="right">';
echo '<div class="admin_date">'.date('M j <b\\r/> H:i', strtotime($row['message_date'])).'</div>';
echo '<div class="admin_bubble">'.$row['message'].'</div>';
echo '<br /><br />';
echo '</div>';
}
$conn = NULL;
// user chat
#$conn = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME . ';charset=utf8', DB_USER, DB_PASS);
#$conn = new PDO('mysql:host=127.0.0.1;dbname=test;charset=utf8', root);
$user = 'root';
$pass = '';
$conn = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->prepare("SELECT * FROM live_chat WHERE user_id = :user_id");
$sth->bindValue(':user_id', '2', PDO::PARAM_INT);
$sth->execute();
foreach ($sth as $row) {
// Test message #1
echo '<div class="user_date">'.date('M j <b\\r/> H:i', strtotime($row['message_date'])).'</div>';
echo '<div class="user_bubble">'.$row['message'].'</div>';
echo '<br /><br />';
}
$conn = NULL;
echo '</div>';
?>
So your screen will be as you expected

Solved my problem with a bit of help from #Eddy Ella.
I first of deleted live_chat_admin and moved receiver to live_chat instead.
And then I used CASE WHEN for switching between id's from user to admin.
Result, exactly as I wanted it.
PHP: http://pastebin.com/GXJEK6u4
SQL: http://sqlfiddle.com/#!2/7081b/5
Result:

Related

Pulling Queries from Database Clears Results on Error vs. Stopping

We have a script that pulls queries from a database every couple of minutes. Those results are then shown in a table on a webpage. It works great, until that database responds with an error code (for whatever reason that may be) and instead of stopping it clears all the data. We don't want this data being cleared. It just needs to stop trying to pull if it gets an error message and wait until the next pull. Any idea how we can prevent this clearing all content?
Connection to Database:
<?php
$constr = 'mysql:host=mysql.test.com;dbname=test_custom;charset=utf8';
$dbUser = 'test';
$dbPW = 'test';
try {
$db = new PDO($constr, $dbUser, $dbPW);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
//$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$rez = "Connected";
//echo $rez;
} catch(PDOException $ex) {
$rez = "An Error occured connecting to the DB: ".$ex->getMessage().".";
//echo $rez;
}
?>
Code to display the results on the page:
<?php
include 'db.connect.php';
$sql = "SELECT ts_id, position, name FROM ts_applications WHERE enable = 1 ORDER BY Client";
$stmt = $db->prepare($sql);
$stmt->execute();
$num_rows = $stmt->rowCount();
//echo $num_rows;
if($num_rows > 0) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$id = $row['ts_id'];
$name = $row['name'];
echo "<tr>";
echo "<th><a href='position.php?id=" . $id . "'>" . $name . "</a></th>";
echo "</tr>";
}
} else {
echo "<tr>";
echo "<th>Please <a href='contact.php'>Contact</a> Doh! Something went wrong</th>";
echo "</tr>";
}
include 'db.close.php';
?>
Thank you in advance!
You might try changing your query to:
$sql = "IF EXISTS (SELECT TOP 1 fm_id FROM mb_searches WHERE fm_id IS NOT NULL) SELECT fm_id, position, client, city, state FROM mb_searches WHERE enable = 1 ORDER BY Client";
I don't know if that will filter out your error message

The best and most secure way to echo results with pdo

Hi i am new to PDO and i just learn how to make a Query, i have read a lot about this everywhere on the internet, without luck, and then i tryed this, but i am still wondering if this is the right way to do it? How is the best way to make this to a class, because when i tryed, i did not got any kind of error, and any respond either.
<?php
require_once 'dbconfig.php';
// (echo test) $name_structure='%s';
// (echo test) $title_structure='%s';
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$sql = 'SELECT *
FROM portfolio';
$q = $conn->prepare($sql);
$q->execute(array('%son'));
$q->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $q->fetch()) {
echo sprintf($name_structure, $r['name']);
echo sprintf($title_structure, $r['title']);
echo sprintf($description_structure, $r['description']);
echo sprintf($img_structure, $r['img']);
echo sprintf($project_end_structure, $r['project_end']);
}
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
As you forgot to explain what is "this" you are trying, here are two possible scenarios:
In case "this" is for getting all the records from database, the code would be
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $conn->query('SELECT * FROM portfolio');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['name'];
echo $row['title'];
echo $row['description'];
echo $row['img'];
echo $row['project_end'];
}
in case "this" is about selecting only certain records, code it as follows
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $conn->prepare('SELECT * FROM portfolio WHERE name LIKE ?');
$stmt->execute(array('%son'));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['name'];
echo $row['title'];
echo $row['description'];
echo $row['img'];
echo $row['project_end'];
}
How is the best way to make this to a class,
PDO is already a class, mind you. So, insead of making it into another, just learn how to use PDO.
i have read a lot about this everywhere on the internet, without luck,
Here you go, I wrote a tutorial that makes sense (at least for anyone who have basic PHP/SQL training), The only proper guide on PDO

Create Prepared SQL Statement where in the SQL Statement already equal values (SQL Injection)

created a form that gets posts by user id. my question is:
how do you convert this to a prepared statement. seen where you assign a var for a value, however how would you prepare a SQL statement that already equals a value in the request? Statement is:
$sql = "SELECT * FROM posts, users WHERE posts.user_id = users.id AND
posts.user_id = ".$_GET['uid'];"
Complete PHP Statement
this code also runs "PHP functions" but should not be needed for writeup (I suspect)
If it does please let me know and I can supply them.
<?php
if(isset($_GET['uid'])) {
$sql="SELECT * FROM posts, users WHERE posts.user_id = users.id
AND posts.user_id = ".$_GET['uid'];
} else {
$sql="SELECT * FROM posts, users WHERE posts.user_id = users.id
ORDER BY post_id DESC";
}
include_once('dbconnect.php');
$result=mysql_query($sql);
if(!$result) {
error_reporting(1);
echo mysql_error();
}
$postID=$_GET['pid'];
while($row=mysql_fetch_array($result)) {
echo $row['post_id'].$row['post_title'].$row['username'];
if(isset($_SESSION['id'])) {
if(getSessionUserId() == $row['user_id']) {
echo $row['post_id'].$row['post_id'];
}
}
echo substr($row['post_content'], 0, 200).$row['post_id'];
}
?>
(1) found out that I needed to create an array that set names to UTF8; once that was done I was able to connect to Server. (2) then needed to send call to server. (3) then fetch results from server [fetchAll()]
<?php
$dsn = 'mysql:host=HOST;dbname=DATABASE';
$username = 'USERNAME';
$password = 'PASSWORD';
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', PDO::ATTR_PERSISTENT => false
);
try
{
$dbh = new PDO($dsn, $username, $password, $options);
echo '<h4 class="text-success">PDO connection created Successfully</h4>';
print '<h4 class="text-info">Connection Info: </h4><p class="text-warning">'.$dsn.'</p>';
print '<p class="text-warning"><b>Username: </b>'.$username.'</p><br />';
}
catch(PDOException $e)
{
echo '<p class="text-danger">'.$e->getMessage().'</p>';
die();
}
$dbh = new PDO($dsn, $username, $password);
$stmt = $dbh->prepare('SELECT * FROM posts, users WHERE posts.user_id = users.id ORDER BY post_id DESC');
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row)
{
echo '<h3>'.$row['post_title'].'</h3>'; #Post Title
echo '<p class="text-success col-md-12" name="marketing-section" id="marketing-section"> Author: '.$row['username'].'</p>';
echo '<p class="lead col-md-12">'.substr($row['post_content'], 0, 200).' ...More</p><br /><hr>';
}
?>
Works Great now! See it at Create Prepared SQL Statement: Demo.

I need a code to incremeny a column in my table when condition is satisfied

The below one is the code i'm using for incrementing,it shows no error but the "like" column is not incrementing.
<?php
$id=$_GET['id'];
echo $id;
$dsn = 'mysql:host=127.0.0.1;dbname=as1';
$user = 'root';
$password = '';
try{
// Connect and create the PDO object
$pdo = new PDO($dsn, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo 'Database connection failed - ';
echo $e->getMessage();
exit;
}
$sql="UPDATE photo SET likes = likes + 1 WHERE imagename=:id";
$q=$pdo->prepare($sql);
$q->execute(array($id));
header("Location:upload.php");
}
$sql="UPDATE photo SET likes = likes + 1 WHERE imagename=':id'";
$sql="UPDATE photo SET likes = likes + 1 WHERE imagename=:id";
$q=$pdo->prepare($sql);
$q->bindParam(':id', $id, PDO::PARAM_INT);
$q->execute();
++ known from programming languages does not work with normal SQL syntax.

MySQL MATCH, AGAINST not works with PDO

I have this simple code to make search results depending on relevance:
$stmt = $db->query('SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")');
$appCount = $stmt->rowCount();
echo $appCount;
And it's not showing any results!
Thanks in advance for your help,
Marcell
Stackoverflow's usability is below zero.
Because there is no way to make a half-screen banner shown to everyone posting a question under PDO tag:
Enable ERRMODE_EXCEPTION when connecting to PDO before asking a question.
Because it is pointless to ask without an error message, yet error message most likely will render a question unnecessary.
$dsn = 'mysql:host=localhost;dbname=test;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
);
$pdo = new PDO($dsn,'root','', $opt);
Try
'SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")'
in phpmyadmin and see if it really returns anything.
try this
<?php
// Connection data (server_address, database, name, poassword)
$hostdb = 'localhost';
$namedb = 'tests';
$userdb = 'username';
$passdb = 'password';
try {
// Connect and create the PDO object
$db = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$db->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
// Define and perform the SQL SELECT query
$sql = "SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")";
$stmt = $db->query($sql);
// If the SQL query is succesfully performed ($stmt not false)
if($stmt !== false) {
$cols = $stmt->columnCount(); // Number of returned columns
echo 'Number of returned columns: '. $cols. '<br />';
// Parse the result set
foreach($stmt as $row) {
echo $row['id']. ' - '. $row['name']. ' - '. $row['category']. ' - '. $row['link']. '<br />';
}
}
$db = null; // Disconnect
}
print_r($sth->errorInfo());
}
?>
enclose your code in try and catch blocks, then you should get a clue to where your going wrong in your SQL syntax:
try {
// your code
} catch ( PDOException £e ) {
echo $e->getMessage();
exit();
}

Categories