Get id from the url

1

I am sending the id by the url, in the view of my browser it is displayed in this way

  

localhost / maybe% 20company / chat / index.php? id = 4

I want that id of the url can be obtained from another file that is called by index.php

my index.php is as follows

<?php session_start();

include 'db.php';
include '../functions.php';

$emit = obtener_mensajes($conexion, $us);

comprobarSession();

?>
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link rel="stylesheet" href="style.css">
    <script>
        function ajax(){
            var req = new XMLHttpRequest();
            req.onreadystatechange = function(){
                if (req.readyState == 4 && req.status == 200) {
                    document.getElementById('chat').innerHTML = req.responseText;
                }
            }

            req.open('GET', 'chat.php', true);
            req.send();

        }

        setInterval(function(){
            ajax()
        }, 1000);
    </script>
</head>
<body onload="ajax();">

<div id="container">
    <div id="chat_box">
        <div id="chat"></div>
    </div>
    <form action="index.php" method="POST">
        <textarea name="message" placeholder="Enter message"></textarea>
        <input type="hidden" name="nombre" placeholder="Name" value="<?php echo $_SESSION['usuario']['nombre']?>">
        <input type="submit" name="submit" value="Send it">
        <?php foreach ($emit as $msg): ?>   
        <input type="hidden" name="idReceiver" value="<?php echo $msg['idEmitter']; ?>">
        <input type="hidden" name="idEmitter" value="<?php echo $us ?>">
        <?php endforeach ?>
    </form>
<?php 

if (isset($_POST['submit'])) {
    $name = $_POST['nombre'];
    $message = $_POST['message'];
    $emitter = $_POST['idEmitter'];
    $receiver = $_POST['idReceiver'];

    $query = "INSERT INTO messages (nombre, message, idEmitter, idReceiver, seenUsuario) VALUES ('$name', '$message', '$emitter', '$receiver', '0')";

    $run = $conexion->query($query);
}

?>
</div>

</body>
</html>

and my chat.php

is the following

<?php session_start();

include 'db.php';
require_once '../functions.php';

comprobarSession(); 

?>



<?php 

$query = "SELECT ue.idUsuario, ue.nombre, ur.nombre, c.sent, c.message FROM messages c
              INNER JOIN usuarios ue ON c.idEmitter = ue.idUsuario
              INNER JOIN usuarios ur ON c.idReceiver = ur.idUsuario
              WHERE (c.idEmitter = 1 AND c.idReceiver = $us)
              or (c.idEmitter = $us AND c.idReceiver = 1)";

$run = $conexion->query($query);

while ($row = $run->fetch(PDO::FETCH_ASSOC)):
    //var_dump($row);

?>

        <div id="chat_data">
            <span style="color: green;"><?php echo $row['nombre']; ?> </span><br>
            <span style="color: brown;"><?php echo $row['message']; ?></span>
            <span style="float: right;"><?php echo fecha($row['sent']); ?></span>
        </div>
<?php endwhile;?>

What I want is to be able to get the id of the url in chat.php to be able to place it in the query, exactly where it has the number 1

I have not managed to find the way I can get it ... I hope someone can help me

  

EDITING

this has been the new code

<?php session_start();

include 'db.php';
require_once '../functions.php';

comprobarSession(); 
$id=$_GET['id'];
var_dump($id);
?>



<?php 

$sql="
        SELECT ue.nombre de, ur.nombre a, c.message FROM  messages c
    INNER JOIN usuarios ue ON c.idEmitter = ue.idUsuario
    INNER JOIN usuarios ur ON c.idReceiver = ur.idUsuario
    WHERE (c.idEmitter = usr1 AND c.idReceiver = :usr2)
    OR (c.idEmitter = :usr2 AND c.idReceiver = usr1)";



/**
 *  Pruebas 
 *  En el código  se usa  PDO y  consultas preparadas
*/


$usr1=$id;
$usr2=$us;

$stmt = $conexion->prepare($sql);
$stmt->bindParam("usr1",$usr1);
$stmt->bindParam("usr2",$usr2);
$stmt ->execute();

$arrDatos = $stmt->fetchAll(PDO::FETCH_ASSOC);
imprimir ($arrDatos);

function imprimir($arrDatos)
{

    if ($arrDatos)
    {
        echo "<hr />SE ENCONTRARON  ".count($arrDatos). " REGISTROS<br /><hr />";
        /**
         *  Construímos los datos  de forma limpia
        */
        $strHtml='CHAT:<br />';    
        foreach ($arrDatos as $row)
        {
            $strHtml.='<span>'.$row["de"].': </span>'.$row["mensaje"].'<br />';
        }
        echo $strHtml;
    }
}

And this what prints on screen index.php

the Url is still the same

  

localhost / maybe% 20company / chat / index.php? id = 1

And if I change to localhost/talvez%20empresa/chat/chat.php?id=1

nothing is shown

    
asked by Cesar Gutierrez Davalos 24.07.2017 в 03:48
source

1 answer

1

You need the following:

In index.php :

Retrieve in JavaScript the id value you want to post.

I guess it's about this: <input type="hidden" name="idReceiver" value="<?php echo $msg['idEmitter']; ?>">

You can put a id tag so you can recover it easier in Javascript. Something like this:

    <input type="hidden" id="myId" name="idReceiver" value="<?php echo $msg['idEmitter']; ?>">

Then you retrieve it in JS, to pass it to chat.php .

Your ajax function should look like this:

    function ajax(){
        var req = new XMLHttpRequest();
        req.onreadystatechange = function(){
            if (req.readyState == 4 && req.status == 200) {
                document.getElementById('chat').innerHTML = req.responseText;
            }
        }

        var myId=document.getElementById('myId');
        var url='chat.php?id='+myId;

        req.open('GET', url, true);
        req.send();

    }

That mode should have a chat.php url similar to this: /chat.php?id=1

In chat.php :

...
$id=isset($_POST['id']);
if ($id)
{

... Todo el código de la base de datos
... Usa consultas preparadas como te expliqué en otra pregunta
... Y usa fetchAll para obtener un array asociativo, no fetch:

while ($row = $run->fetchAll(PDO::FETCH_ASSOC)):

}else{
echo "No se recibió la variable id";
}
    
answered by 24.07.2017 в 04:13