php mysqli not working - php

I am making a chat application and this is the part that checks for new additions.
<?php
$servername = "*";
$username = "*";
$password = "****";
$dbname = "*";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (mysqli_connect_error($conn)) {
die("Connection failed: " . mysqli_connect_error($conn));
}
$id = $_GET['id'];
$sql = "SELECT position, user, comment,time FROM chat WHERE position > $id";
$result = mysqli_query($conn,$sql);
if (mysqli_num_rows() > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$row2 = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM login WHERE username=".$row['user']));
$userImage = $row2["avatar"];
echo "<div class='container-fluid well'><p class='left'>"."<img class='img-circle zoom' src='/profile_images/".
$userImage
."' style='width:32px;height:32px;'>".$row["user"]. ": " . $row["comment"]. "</p><h4><small class='right'> at ".$row['time']."</small></h4></div>";
}
}
mysqli_close($conn);
?>
it was working until I changed the line
$row2 = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM login WHERE username=".$row['user']));
Help would be appreciated.
Update:
this is my html:
There is more. but this is the most important
<div id='newchat'></div>
<script>
$(document).ready(function(){
getChat();
var id = <?php echo $id ?>;
function getChat(){
setTimeout(getChat,1000);
$.get("getChat.php?id="+id,function( text ) {
if (text != ""){
id ++;
$( "#newchat" ).prepend( text );
}
});
}
});
</script>

Try this query :
$row2 = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM login WHERE username='{$row['user']}'"));
Side note : Your query is unsafe. Read this
How can I prevent SQL injection in PHP?.

you forget 2 '
$row2 = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM login WHERE
username='".$row['user']."'"));

Simply use this query:
"SELECT * FROM login WHERE username='".$row['user']."'"
instead of
"SELECT * FROM login WHERE username=".$row['user']
and if you want a simple query then use:
$usr = $row['user'];
$row2 = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM
login WHERE username=$usr"));
It'll definitely work.

Write your query as below:-
$sql = "SELECT * FROM login WHERE username='{$row['user']}'";
mysqli_fetch_assoc(mysqli_query($conn,$sql));
Hope it will help you :)

Related

php can't connect to database after using ajax

So I'm trying to delete a comment on the website and also from database, but it just works find on web site. After I click delete button, the comment is gone, but nothing changed in my database. After I refresh the page, the comments I deleted appear again.
So I think, somehow, ajax makes php disconnect to MySQL database anymore.
jquery:
$(".delete").each(function (index4) {
$(this).on("click",function (event) {
$(this).parent().parent().load("../public/form/delete_comments.php", {index4:index4}, function () {
$(this).remove();
});
})
php:
<?php
require_once "../../private/initialize.php";
$id = $_SESSION['id'];
$thread_clicked = isset($_POST['index4'])?$_POST['index4']:'';
$req_user = "SELECT * FROM log_in WHERE id='" .$id. "'";
$result_user = mysqli_query($db,$req_user);
$subject_user = mysqli_fetch_assoc($result_user);
$req = "DELETE FROM comments WHERE user=`" .$subject_user['account']. "` AND c_id=`" .$thread_clicked. "`";
$result = mysqli_query($db,$req);
UPDATE: i changed ajax to :$(this).parent().parent().load("/yyqGS/public/form/delete_comments.php",{index4:index4});
but still doesn't do any change to database.
UPDATE:
<?php
require_once "../../private/initialize.php";
session_start();
$id = $_SESSION['id'];
$thread_clicked = isset($_POST['index4'])?$_POST['index4']:'';
$thread_clicked = $thread_clicked +1;
$req_user = "SELECT * FROM log_in WHERE id='.$id.'";
$result_user = mysqli_query($db,$req_user);
$subject_user = mysqli_fetch_assoc($result_user);
$req = "DELETE FROM comments WHERE user='" .$subject_user['account']. "' AND c_id='" .$thread_clicked. "'";
$result = mysqli_query($db,$req);
if ( !$req ) {
printf("Error: %s\n", $mysqli_error($db));
}
else{
echo $result;
}
and i got 1 everytime i delete a comment, but database still doesn't change!
Magic just happened! I don't even know what have I done (I fixed quotation marks problem), but it just works know!
<?php
require_once "../../private/initialize.php";
session_start();
$id = $_SESSION['id'];
$thread_clicked = isset($_POST['index4'])?$_POST['index4']:'';
$thread_clicked = $thread_clicked +1;
$req_user = "SELECT * FROM log_in WHERE id='".$id."'";
$result_user = mysqli_query($db,$req_user);
$subject_user = mysqli_fetch_assoc($result_user);
$req = "DELETE FROM comments WHERE user='" .$subject_user['account']. "' AND c_id='" .$thread_clicked. "'";
$result = mysqli_query($db,$req);
if ( !$req ) {
printf("Error: %s\n", $mysqli_error($db));
}
else{
echo $req;
}
?>
<?php
require_once "../../private/initialize.php";
$id = $_SESSION['id'];
$thread_clicked = isset($_POST['index4'])?$_POST['index4']:'';
$req_user = "SELECT * FROM log_in WHERE id='$id'";
$result_user = mysqli_query($db,$req_user);
$subject_user = mysqli_fetch_assoc($result_user);
$req = $result = mysqli_query($db,$req);
$req = "DELETE FROM comments WHERE user='"$subject_user['account']"' AND c_id='"$thread_clicked"'";
$result = mysqli_query($db,$req);
Try this code for your php. If it works fine i will edit with explanation.
Your using the wrong quotes in your delete statement - your using back ticks which is used to identify fields, not surround values.
$req = "DELETE FROM comments WHERE user=`" .$subject_user['account']. "` AND c_id=`" .$thread_clicked. "`";
should be
$req = "DELETE FROM comments WHERE user='" .$subject_user['account']. "' AND c_id='" .$thread_clicked. "'";
with single quotes rather than backticks.
Edit: It's also useful to check the return values from queries...
if ( !$result ) {
printf("Error: %s\n", $mysqli_error($db));
}
Should let you know if there are any problems with the delete.

How to pull data with a link on a different page with mysqli

I figured out the way to link to the page and set what ID i would like to call:
CLICK TEST **(IS THIS RIGHT?)**
But then I need page.php to pull the id, this is what I am using at the moment to pull the id manually. How would I make the following code pull it form the link?
<?php
$query = "select * from Drinklist where id = 10";
$result = mysqli_query($conn,$query);
while($Drinklist = mysqli_fetch_array($result)){
echo "<head>";
echo "<title>".$List['name']." - Site Name</title>";
}
?>
I tried the following (didn't work):
$query = "select * from List where id = . $id";
Seems like I can only find the way to do it with MYSQL and not MYSQLI... Any help would be appreciated.
UPDATED CODE:
<?php
$query = "select * from Drinklist where id = ?";
$result = mysqli_prepare($conn,$query);
mysqli_stmt_bind_param($result, 'i', $_GET['id']);
mysqli_stmt_execute($result);
while($Drinklist = mysqli_fetch_array($result)){
echo "<head>";
echo "<title>".$Drinklist['name']." - Mixed Drinks Station</title>";
}
?>
Getting error:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result,
object given in public_html/page.com/test/inc/drink-page.php on line 6
Ok so I ended up figuring this one out with a ton of trial and error...
Thank you chris85 for the early support and hopefully this can help you out a little. This is fun ;)
<?php
$server = "localhost";
$user = "user";
$pass = "password";
$dbname = "database";
//Creating connection for mysqli
$conn = new mysqli($server, $user, $pass, $dbname);
//Checking connection
if($conn->connect_error){
die("Connection failed:" . $conn->connect_error);
}
$article_id = $_GET['id'];
if( ! is_numeric($article_id) )
die("Looks like you are lost! <a href='#'>Back to Home</a> ");
$query = "SELECT * FROM `Whatever` WHERE `ID` =$article_id LIMIT 0 , 30";
$info = mysqli_query($conn,$query);
while($row = mysqli_fetch_array($info, MYSQL_ASSOC))
{
$name = $Whatever['name'];
$description = $Whatever['description'];
$keywords = $Whatever['keywords'];
$lrgpic = $Whatever['lrgpic'];
$vid = $Whatever['vid'];
$name = htmlspecialchars($row['name'],ENT_QUOTES);
$description = htmlspecialchars($row['description'],ENT_QUOTES);
$keywords = htmlspecialchars($row['keywords'],ENT_QUOTES);
$lrgpic = htmlspecialchars($row['lrgpic'],ENT_QUOTES);
$vid = $row['vid']; //Use <-- to be able to have HTML in your database otherwise the above would remove <, >, /, ', ", ect.
echo "<head>";
echo "<title>$name - Site title</title>";
echo "<meta name='description' content='$description'>";
echo "<meta name='keywords' content='$keywords'>";
include 'inc/head.php'; //includes already are in a php file ;)
echo "</head>";
echo "<body>";
include 'inc/header.php';
include 'inc/nav.php';
echo "<div class='wrapper'>";
echo "<div id='drink-name'>";
echo "<h2>$name</h2>";
echo "</div>";
// AND SO ON
}
?>

How do I retrieve a single row from a table using PHP?

I've created a table and stored values in it. The table has a column 'ID' which is unique.
Now I’ve created a form where there is a button marked Retrieve. When I enter the ID and click the Retrieve button, I want to view the data corresponding to this ID.
How do I do this using PHP and MYSQL?
I’ve got some code below, but it isn‘t working. No error message is being showed. But there is no problem with the db connection. Rest of the functions working except for 'RETRIEVE'.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'DB';
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_error())
{
die("couldn't connect" . $conn->connect_error());
}
echo ("connected successfully");
$id = $_POST['Id'];
$name = $_POST['Name'];
$blood = $_POST['BloodGroup'];
if(isset($_POST['insert'])){
$insert = "Insert into ins(Id, name, BloodGroup) values ('$id','$name', '$blood')" ;
if($conn->query($insert) === TRUE) {
echo ("Input data entered successfully");
} else {
echo ("Input data failed to be entered" . $conn->error());
}
$conn->close();
} elseif(isset($_POST['update'])) {
$update = "update ins set Name='".$name."', BloodGroup='".$blood."' where Id='".$id."'";
mysql_query($update);
if($conn->query($update) === TRUE) {
echo ("Data updated successfully");
} else {
echo ("Data cant be updated" . $conn->error());
}
$conn->close();
} elseif(isset($_POST['delete'])) {
$id = $_POST['Id'];
$delete = "delete from ins where Id='".$id."'";
if($conn->query($delete) === TRUE) {
echo ("Data deleted successfully");
} else {
echo ("Data cant be updated" . $conn->error());
}
$conn->close();
}
else {
$id = $_POST['Id'];
$retrieve = "SELECT * FROM ins WHERE Id = ".'$id'."";
$dis = $db->query($retrieve);
$row = $dis->fetch_assoc();
echo 'Details are: '.$row['id'];
}
}
$conn->close();
?>
Change sql select clause into this:
"SELECT * FROM ins WHERE Id = " .$id. " LIMIT 1";
$retrieve = "SELECT * FROM ins WHERE Id = ".$id." LIMIT 1";
The limit will work for you
In the SQL statement ($retrieve), the single quotes are killing it for you. Try either of the following:
Remove the single quotes around $id and keep the rest of the statement the same
Change '$id' to "'{$id}'" (if you're keen on getting the single quotes around the $id value - just in case $id is a text value and not a number)
Try this
$retrieve = "SELECT * FROM ins WHERE Id = ".$id;
$dis = $db->query($retrieve);
$row = $dis->fetch_row();

trying to do SELECT in php but i get

So I got a nifty little bit of code set to run along and find me information when I give it a certain KittenID but its not working at all, I am sad. And oh so tired, Can anyone tell me where I have gone wrong? and yes I do have:
<?php
date_default_timezone_set('America/New_York');
//If statements:
//find:
date_default_timezone_set('America/New_York');
if(isset($_POST['Find']))
{
$connection = mysql_connect("ocelot.aul.fiu.edu","userName","password");
// Check connection
if (!$connection)
{
echo "Connection failed: " . mysql_connect_error();
}
else
{
//select a database
$dbName="spr15_xgotz001";
$db_selected = mysql_select_db($dbName, $connection);
//confirm connection to database
if (!$db_selected)
{
die ('Can\'t use $dbName : ' . mysql_error());
}
else
{
$result = mysql_query($connection,"SELECT * FROM Kittenz WHERE KittenID =<?php$_POST[KittenID]?>;)
while($row = mysql_fetch_array($result))
{
$Name = $row['Name'];
$KittenID = $row['KittenID'];
$KittenAge = $row['KittenAge'];
$Email = $row['Email'];
$Comments = $row['Comments'];
$Gender = $row['Gender'];
$Personality = $row['Personality'];
$Activity = $row['Activity'];
echo $row['Comments'];
}
}
}
mysql_close($connection);
}
?>
Use
$result = mysql_query($connection,"SELECT * FROM Kittenz WHERE KittenID = " .$_POST['KittenID']);
instead of
$result = mysql_query($connection,"SELECT * FROM Kittenz WHERE KittenID =<?php$_POST[KittenID]?>;)
Note: Please use mysqli_ for your future projects
You need to privide more context. How are you setting the $_GET['id'].. is it in fact being stored as $_GET['KittenID'] (e.g. https://yoursite.com?view&KittenID=1). If so...
You can set a variable and declare the 'KittenID'
$kittenid = $_POST['KittenID'];
$result = mysql_query($connection,"SELECT * FROM Kittenz WHERE KittenID = $kittenid");
I suggest providing more context. What error are you getting? What do your parameters look like?
Use
$result = mysql_query($connection,"SELECT * FROM Kittenz WHERE KittenID = " .$_SERVER['KittenID']);
instead of
$result = mysql_query($connection,"SELECT * FROM Kittenz WHERE KittenID =<?php$_POST[KittenID]?>;)

PHP - MYSQL - Display Pages by id from One php file

I have a problem to do the code work...I don't know why its not working...I want to display from the database title and many other by id...The name of the file is view.php...If I want to show id 1 then I type on url view.php?id=1 or id 2 view.php?id=2...here is my code please help me out...
<?php
$getid = $_GET["id"];
$dbuser = 'user';
$userpass = 'pass';
$database = 'db';
error_reporting(0);
$con = mysql_connect("localhost",$dbuser,$userpass);
if(!$con){die('Could not connect:'.mysql_error());}
mysql_select_db($database, $con);
mysql_query("SET NAMES utf8");
date_default_timezone_set('Europe/Athens');
$query = mysql_query("SELECT id,title,description FROM player WHERE id = '$getid'");
if(mysql_num_rows($query)){
$result = mysql_fetch_assoc($query);
$id = $result['id'];
$title = $result['title'];
$description = $result['description'];
echo 'ID: '.$id.'<br />Title: '.$title.'<br />Description: '.$description;
}else{
echo 'Error';
exit;
}
?>
Change this:
if(mysql_num_rows($query)){
to this:
if(mysql_num_rows($query) >= 1){
keep in mind that you've got to have things in your database with the ID that you give,
or it will just go to else again.
(mysql_num_rows returns FALSE or an integer with the amount of rows, and since the if statement didnt check for an integer but for true, it always went down the ELSE path)
Source: PHP.net
<?php
$query = mysql_query("SELECT id,title,description FROM player WHERE id = '$getid'");
$count = mysql_num_rows($query);
if($count != 0){
while($result = mysql_fetch_array($query)){
$id = $result['id'];
$title = $result['title'];
$description = $result['description'];
echo 'ID: '.$id.'<br />Title: '.$title.'<br />Description: '.$description;
}
}else{
echo 'Error';
}
?>

Categories