PHP select from statement - php

I'm trying to do a php select statement like this:
$select = mysql_query("select * from message where receiver_id = '$receiver_id'and frm_id = '$frm_id' ORDER BY id DESC");
while($row = mysql_fetch_array($select))
{
$id = urlencode(encryptor('encrypt', $result['user_id']));
$query = mysql_query($sql);
$result = mysql_fetch_assoc($query);
}
But its not working instead its select from table where frm_id = $frm_id only.

Using PDO you can do something like:
$id = "Id wanted here";
$conn = new PDO("server", "username", "password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->prepare("SELECT * from `tablename` WHERE `receiver_id` = :id");
$sth->bindParam(':name', $id);
$sth->execute();

I think there are two errors.
1: you are using $result['user_id'] before defining $result.
2: $sql isn't defined.
also i am not sure about encryptor method.

You can try:
$select= mysql_query("select * from message where receiver_id = $receiver_id
and frm_id = $frm_id ORDER BY id DESC");
or
$select= mysql_query("select * from message where receiver_id = $receiver_id
or frm_id = $frm_id ORDER BY id DESC");

Related

How do I add a string at the end of user input in SQL/PHP

I have a SQL query that is based on user input.
However, in the table, theres a "-1" at the end of every word that you search for.
For example if you want to get the sql result of car, it's actually named car-1 in the database, but the user should only be able to search for car.
This is how its setup:
$sql = "SELECT * FROM that WHERE this = ?";
$stmt = $conn->prepare($sql);
$search_query = $_POST['this'];
$stmt->bind_param('s', $search_query);
$stmt->execute();
$result = $stmt->get_result();
What I want, is that the select query should be like:
$sql = "SELECT * FROM that WHERE this = ? + '-1'";
But ^^ doesn't work.
$sql = "SELECT * FROM test WHERE NAME='car' & -1";
test = that
NAME= table name
'car' = this
Why don't you just concat -1 to search_query :
$sql = "SELECT * FROM that WHERE this = ?";
$stmt = $conn->prepare($sql);
$search_query = $_POST['this'];
$stmt->bind_param('s', $search_query.'-1');
$stmt->execute();
$result = $stmt->get_result();
Using MySQL:
$sql = "SELECT * FROM that WHERE this = CONCAT(?, '-1')";
Using PHP:
$stmt->bind_param('s', $search_query . "-1");

How to select table by php var when use in mysqli bind_param?

Normally i use this code, it's work good.
<?PHP
include("connect.php");
$xxx = "275";
$sql = 'SELECT * FROM test_table WHERE number <= ? order by id desc';
$statement = $db_mysqli->prepare($sql);
$statement->bind_param('s', $xxx);
$statement->execute();
$result = $statement->get_result();
$row = $result->fetch_array(MYSQLI_ASSOC);
$number = $row['number'];
echo $total_price;
?>
Then i apply code by use php var for select table. like this
<?PHP
include("connect.php");
$xxx = "275";
$table_name = "test_table";
$sql = 'SELECT * FROM ? WHERE number <= ? order by id desc';
$statement = $db_mysqli->prepare($sql);
$statement->bind_param('ss', $table_name , $xxx);
$statement->execute();
$result = $statement->get_result();
$row = $result->fetch_array(MYSQLI_ASSOC);
$number = $row['number'];
echo $total_price;
?>
But not get any data, how can i do ?
You cannot bind to a table name. You will need to write your code as:
$table_name = "test_table";
$sql = "SELECT * FROM $table_name WHERE number <= ? order by id desc";
$statement = $db_mysqli->prepare($sql);
$statement->bind_param('s', $xxx);

Select Only one result for each user id for a "chat history"

Trying to return only one (latest) row of each UserId if contained in MySQL DB to have results show a "chat history" per-say. Basically like a test history overview of the latest message to or from any other user.
<?php
$userId = $_POST['userId'];
$pdo = new PDO('mysql://hostname=localhost;dbname=data_base', 'user', 'password');
$query = $pdo->query("SELECT * FROM `messages` WHERE `from_id`='{$userId}' OR `to_id`='{$userId}' ORDER BY `stamp` DESC");
$data = $query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($data);
<?php
$userId = $_POST['userId'];
$pdo = new PDO('mysql://hostname=localhost;dbname=data_base', 'user', 'password');
$query = $pdo->query("SELECT * FROM `messages` WHERE `from_id`='{$userId}' OR `to_id`='{$userId}' GROUP BY `from_id`, `to_id` ORDER BY `stamp` DESC");
$data = $query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($data);

How can i change this select sql statement into another select sql?

I have code the below code works fine but i want to have one sql statement instead of few in this code so when i try to change into one i get an error.
$eventID = $_GET['id'];
$sql = "SELECT * FROM te_events where eventID='$eventID'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{
$eventTitle = $row['eventTitle'];
$eventDescription = $row['eventDescription'];
$eventStartDate = $row['eventStartDate'];
$eventEndDate = $row['eventEndDate'];
$eventPrice = $row['eventPrice'];
$venueID = $row['venueID'];
$catID = $row['catID'];
$sql2 = "SELECT * FROM te_venue where venueID='$venueID'";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc())
{
$venueName = $row2['venueName'];
}
$sql3 = "SELECT * FROM te_category where catID='$catID'";
$result3 = $conn->query($sql3);
while($row3 = $result3->fetch_assoc())
{
$catName = $row3['catDesc'];
}
}
?>
I changed the code into this but it seems it is not working.
<?php
$eventID = $_GET['id'];
$sql = "SELECT * FROM te_events where eventID='$eventID' AND where venueID='$venueID' From te_venue AND where catID='$catID' From te_category";
$queryresult = mysqli_query($conn, $sql) or die(mysqli_error($conn));
while ($row = mysqli_fetch_array($queryresult)) {
$eventTitle = $row['eventTitle'];
$eventDescription = $row['eventDescription'];
$eventStartDate = $row['eventStartDate'];
$eventEndDate = $row['eventEndDate'];
$eventPrice = $row['eventPrice'];
$venueID = $row['venueID'];
$catID = $row['catID'];
$catName = $row['catDesc'];
$venueName = $row['venueName'];
}
?>
And i get this error.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where venueID='' From te_venue AND where catID='' From te_category' at line 1
Yes, you can do that. But in order to get the fields that you want from all three tables, you have to join them together.
Look at this article on W3S: http://www.w3schools.com/sql/sql_join.asp. It explains SQL JOIN syntax and the basic theory behind.
If you just joined venue and event Your select statement looks like:
SELECT * FROM te_event
JOIN te_venue
ON te_vendue.venueID = te_event.venueID
WHERE te_event.eventID = $eventID
The category table is similar.
Note: In general, use of SELECT * is discouraged. Your should list the fields that you want returned from the tables. ie. SELECT te_eventID, te_venueID
You could use joins as below;
SELECT * FROM te_events
JOIN te_venue ON te_events.venueID = te_venue.venueID
JOIN te_category ON te_events.catID = te_category.catID
WHERE eventID = :EventID
As mentioned you should also use PDO's:
define( "DB_DSN", "mysql:host=localhost;dbname=foo");
define( "DB_USERNAME", "root");
define( "DB_PASSWORD", "password" );
// define sql
$sSQL = "SELECT * FROM te_events
JOIN te_venue ON te_events.venueID = te_venue.venueID
JOIN te_category ON te_events.catID = te_category.catID
WHERE eventID = :EventID";
// create an instance of the connection
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
// prepare
$st = $conn->prepare( $sSQL );
// securely bind any user input in the query
$st->bindValue(":EventID", $iEventID, PDO::PARAM_INT);
// execute the connection
$st->execute()
$aResults = array();
// loop over results and store in aResults
while($row = $st->fetch()){
$aResults[] = $row;
}
// output data
foreach($aResults as $aResult){
echo "title: ".$aResult['eventTitle'];
}
You should always avoid using select *. Especially when your doing joins. Ensure you request only what you need and alias if you require duplicate column names

how do i implement update i pdo for the following mysql code?

here is my mysql code and equivalent pdo code i need to know what is wrong
$id = $_POST['id'];
$query1=mysql_query("SELECT Quantity,id FROM `yumyum`.`food` where `food`.`id` LIKE $id");
$r = array();
while($r = mysql_fetch_assoc($query1)) {
$output = $r['Quantity'];
echo $output;
$query2=mysql_query("UPDATE food SET Quantity = Quantity - 1 where `food`.`id` LIKE ".$r["id"]);
PDO code
$stmt = $db->prepare("SELECT * FROM yuymuym WHERE id=:id AND Quantity=:Quantity");
$stmt->execute(array($id, $Quantity));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC)
How about this. I don't know what $_POST['id'] is so you have to figure the rest youself. It updates every item with id in $ids array. So this updates items with id 1,2,3,4 and 5.
$db = new PDO('mysql:host=localhost;dbname=yumyum', 'username_here', 'password_here');
$ids = array(1,2,3,4,5);
foreach($ids as $id){
$stmt = $db->prepare("SELECT Quantity, id FROM `food` WHERE `food`.`id` = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
$row = $stmt->fetch();
if($row){
//uncomment to see $row content
//var_dump($row);
$rowId = (int)$row['id'];
$rowQuantity = (int)$row['Quantity'];
echo $rowQuantity;
$ustmt = $db->prepare("UPDATE `food` SET `Quantity` = `Quantity` - 1 WHERE `food`.`id` = :id");
$ustmt->bindParam(':id',$rowId);
$ustmt->execute();
}else{
var_dump($stmt->errorInfo());
}
}
But PDO basics:
Query (Works with select, insert, update, everything else):
$id = (int)$_POST['id'];
$else = $_POST['string'];
// Connect to database
$db = new PDO('mysql:host=HOST_HERE;dbname=DATABASENAME_HERE', 'USERNAME_HERE', 'PASSWORD_HERE');
// First we prepare our query
$stmt = $db->prepare("... WHERE `id` = :id AND `something` = :else");
// We bind values to our prepared query
$stmt->bindParam(':id',$id);
$stmt->bindParam(':else',$else);
// We execute our query
$success = $stmt->execute();
// If we want to fetch only one row:
$row = $stmt->fetch();
echo $row['id'];
// If we want to fetch all rows:
$rows = $stmt->fetchAll();
foreach($rows as $row){
echo $row['id'];
}
These are very basics, if you don't understand what is really happening here, you should learn some more.

Categories