Select and Decrease field value on mysql query - php

I have a problem with mysql_query
I tried to find members who are online, there is a field "Online" in the members table are always updated with the time server. This is the query.
$ now = time ();
$ olline = mysql_num_rows (mysql_query ("select * from members where gender = 'Man' and (online - '$ now')> 10"));
in phpmyadmin there are 7 members in accordance with the above query. tp I get a value of 0. what is wrong with my code. tq for the answer and sorry for bad english

You should try and always use Mysqli these days as before long Mysql will be gone completely. Mysqli example of your code:
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$now = time(); // The time now for query calc
$gender = "Man"; // Gender for query
$stmt = $mysqli->stmt_init(); //Initialise statement
$stmt->prepare("SELECT * FROM members WHERE gender = ? AND (online - ?)> 10"); //Prepare the query
$stmt->bind_param('ss', $gender, $now); //Assign the query parameters
$stmt->execute(); // Execute the query
$stmt->store_result(); // store result of prepared statement
echo $stmt->num_rows;
$stmt->free_result(); //free up the $stmt var

Variable names cannot contain spaces, so your variable names are invalid. It should be $now or $_now and NOT $ now. See Language variable basics for more information:
Correct code :
$now = time ();
$olline = mysql_num_rows (mysql_query ("select * from members where gender = 'Man' and (online - '$now')> 10"));
Also , avoid using mysql_ functions cause they are deprecated. Use mysqli_ or PDO.

I am not sure, I have clearly understood your question.
If I have understood correctly, you want to display the online available members.
Do you have any flag for checking if the member online or not? If there is a flag then use that flag and filter by online status. This how we have to do for chat operations.
I am not sure, why you going with subtraction.

Related

Select all posts made on the same date

I have a table structure like this:
sender| receiver| message|date|time
----------------------------------
How do I select all the messages written on the same date, with them appearing at the top, just like Facebook Chat?
I've tried something like this:
<?php
$con=mysql_connect("localhost","root","");
$db=mysql_select_db ("chat",$con);
$query=" select * from chat where sender='$send'
and receiver='$rec' order by date";
$result=mysql_query($query);
while($r2=mysql_fetch_array($result))
echo "<div>{$r2['date']}</div>";
{
echo"<div>{$r2['message']}</div>";
}
?>
You're trying to run an SQL query directly from PHP, which you can't do - you'll need to connect to your database first. Then you need to pass the $send and $rec variables to your database, preferably through prepared statements to prevent SQL injection.
It depends on whether you're using MySQLi or PDO as to exactly how you should do that, but I'll assume you're not using the mysql_ constructor, as that was deprecated as of PHP 5.5, and is removed in PHP 7.
As such, here's an example of how to do this through MySQLi with prepared statements:
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
$stmt = $mysqli->prepare(
"SELECT * FROM tablename WHERE sender = ? && receiver = ?");
$stmt->bind_param("ss", $send, $rec);
// "ss' is a format string, each "s" means string
// Each variable gets passed to the question marks, in order
$stmt->execute();
$stmt->bind_result($result);
You then have the results stored in $result, and are free to manipulate from there.
Hope this helps! :)

PHP - Get variable from database based on another variable

I am using PHP to do some database projects for school in a self pace class, so I don't know much of the syntax. I am trying to change a row of by database based on the ID given.
Heres some pseudocode of what I want to accomplish:
if(databaseRowWithThis$id name == x)
UPDATE database SET name = '$name' WHERE id='$id';
If this is confusing, please tell me and I'll try to clear it up.
Thanks in advance.
PHP with Syntax
$conn = mysqli_connect($server,$login,$pw,$database); // connection info
$sql = "UPDATE yourtablename SET name= ? WHERE id=?"; // placeholders for parameters
$stmt = $conn->prepare($sql); // prepare the query
if($stmt){
$stmt->bind_param("is",$id,$name); // bind the parameters to the ?, i for integers, s for string, must be in exact order as the query
$stmt->execute(); // execute
$stmt->close(); // close statement
}
$conn->close(); // close the connection

How can I write a php code for data can not find in table of MySQL database?

I am so sorry mybe it is a silly question but as I am new in web language and php I dont know how to solve this problem.
I have a code which is getting ID from user and then connecting to MySQL and get data of that ID number from database table and then show on webpage.
But I would like to what should I add to this code if user enter an ID which is not in table of database shows a message that no data found.
Here is my code:
<?php
//connect to the server
$connect = mysql_connect ("localhost","Test","Test") ;
//connection to the database
mysql_select_db ("Test") ;
//query the database
$ID = $_GET['Textbox'];
$query = mysql_query (" SELECT * FROM track WHERE Code = ('$ID') ");
//fetch the results / convert results into an array
$ID = $_GET['Textbox'];
WHILE($rows = mysql_fetch_array($query)) :
$ID = 'ID';
echo "<p style=\"font-color: #ff0000;\"> $ID </p>";
endwhile;
?>
Thank You.
Sorry if it is so silly question.
You should use PDO (great tutorial here: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers ). This way, you can develop safer applications easier. You need to prepare the ID before inserting it to the query string, to avoid any user manipulation of the mysql query (it is called sql injection, guide: http://www.w3schools.com/sql/sql_injection.asp ).
The main answer to your question, after getting the results, you check if there is any row in the result, if you got no result, then there is no such an ID in the database. If you use PDO statements $stmt->rowCount();.
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$stmt = $db->prepare("SELECT * FROM table WHERE Code=?");
$stmt->bindValue(1, $id, PDO::PARAM_INT); // or PDO::PARAM_STR
$stmt->execute();
$row_count = $stmt->rowCount();
if ($row_count > 0) {
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
//results are in $results
} else {
// no result, no such an ID, return the error to the user here.
}
Another reason to not use mysql_* functions: http://php.net/manual/en/migration55.deprecated.php

Using variables in MYSQL SELECT WHERE query

I'm trying to include variables in my MYSQL SELECT WHERE query.
I want to be able to use variables, as well as the false symbol "!="
For example:
select * from XXX
where id != '$id'
Why is this not working, and how can I make this work?
It's better you use mysqli prepared statement or PDO since mysql_* functions are deprecated in recent PHP versions. Check how your query looks with mysqli prepared statement.
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("SELECT * XXX WHERE id != ?");
$stmt->bind_param( "d", $value);
// 'd' is a format integer, for string use 's'
$stmt->execute();
$stmt->bind_result($col1);
// then fetch and close the statement
As you are asking how can pass variable id in mysql query so check below, other wise so many guys have answered you for php etc.
set #id=4;
select * from XXX
where id != #id;
If you are using this code in php, you can use this
$query = "select * from XXX where id != {$id}";
OR
$query = "select * from XXX where id != '".$id."'";
If you are trying to use these variables in phpmyadmin, I think that is not possible.

Passing PHP variable to SQL query

$user = mysql_real_escape_string($_POST["userlogin"]);
mysql_connect("uritomyhost","myusername","password");
mysql_select_db('mydatabase');
mysql_query('UPDATE table SET field = field + ($userlogin)');
Is this the right way of getting userlogin from the post request and then inserting it to my SQL query?
Stop using outdated functions and use PDO instead.
$stmt = PDO::prepare('UPDATE table SET field = field + :field');
$stmt->execute(array('field' => $_POST["userlogin"]));
Read some information about PDO.
In short: it escapes your data for you, is quite consistent across databases and generally just easier.
you should use mysql_real_scape_string() just after connecting to database ...
so change your code to this :
mysql_connect("uritomyhost","myusername","password");
mysql_select_db('mydatabase');
$userlogin = mysql_real_escape_string($_POST["userlogin"]);
mysql_query("UPDATE table SET field = '$userlogin'");
Try like this.
$user = mysql_real_escape_string($_POST["userlogin"]);
mysql_connect("uritomyhost","myusername","password");
mysql_select_db('mydatabase');
mysql_query("UPDATE table SET field = value where user='$user'");
Try this
mysql_query("UPDATE table SET field = field + ('$user')");
However,
You might be updating all the fields in your table because you have no where in your UPDATE clause
Shouldn't it rather be
mysql_query("UPDATE table SET field = field WHERE user= '$user'");
I think you want to INSERT instead of using Update. Why field = field + ($userlogin)? This will concatenate the values. And one more thing please use PDO or MYSQLI
Example of using PDO extension:
<?php
$stmt = $dbh->prepare("INSERT INTO tanlename (field) VALUES (?)");
$stmt->bindParam(1, $user);
$stmt->execute();
?>
Use mysql_real_escape_string() after mysql connection and
Use double quotes
mysql_query("UPDATE table SET field = field + ({$userlogin})");
Use mysqli_query for you queries(notice the i) and use prepared statements. Using prepared statements is more secure than using straight queries and including the variable in the query string. Moreover, mysql will be deprecated soon. Example :
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$city = "Amersfoort";
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>

Categories