I'm having a problem with running this function. When it runs, it does exactly what I want, except that within my like_requests table the request_id is not the mysql query result linked to the variable $select but Resource Id #22. I thought that resource id's appear when you are trying to echo out a result, but I'm not using echo. What's wrong with the code?
function update_likes($band_requested, $new_likes, $session_user_id) {
$select = mysql_query("SELECT `primary_id` FROM `requests` WHERE
`user_requester_id` = '$session_user_id' AND `person_requested` =
'$band_requested'");
$sql_2 = "INSERT INTO `like_requests` (user_id, request_id) VALUES
('$session_user_id', '$select')";
mysql_query($sql_2);
}
$band_requested = 'rally done';
$new_likes = 239;
$the_session_user_id = 3;
update_likes($band_requested, $new_likes, $the_session_user_id);
UPDATE WITH CORRECTED ANSWER
Here is the code corrected with help from David.
function update_likes($band_requested, $new_likes, $session_user_id)
{
$select = mysql_query("SELECT `primary_id` FROM `requests` WHERE `user_requester_id` =
'$session_user_id' AND `person_requested` = '$band_requested'");
$row = mysql_fetch_row($select);
$request_id = $row[0];
$sql_2 = "INSERT INTO `like_requests` (user_id, request_id) VALUES ('$session_user_id',
'$request_id')";
mysql_query($sql_2);
}
mysql_query returns a resource (http://php.net/manual/en/function.mysql-query.php) not just a scalar value. You'd need to use a function like mysql_fetch_row() to get the, presumably, one row you want, assign that row to a variable $row, then retrieve the primary_id with array syntax like $row['primary_id']. By the way, apparently mysql_query is being eased out and we should use the MySQLi API with the mysqli_query() method.
Related
I have a query, and I want to get the last ID inserted. The field ID is the primary key and auto incrementing.
I know that I have to use this statement:
LAST_INSERT_ID()
That statement works with a query like this:
$query = "INSERT INTO `cell-place` (ID) VALUES (LAST_INSERT_ID())";
But if I want to get the ID using this statement:
$ID = LAST_INSERT_ID();
I get this error:
Fatal error: Call to undefined function LAST_INSERT_ID()
What am I doing wrong?
That's because that's an SQL function, not PHP. You can use PDO::lastInsertId().
Like:
$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();
If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:
$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();
lastInsertId() only work after the INSERT query.
Correct:
$stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass)
VALUES(?,?,?);");
$sonuc = $stmt->execute([$username,$email,$pass]);
$LAST_ID = $this->conn->lastInsertId();
Incorrect:
$stmt = $this->conn->prepare("SELECT * FROM users");
$sonuc = $stmt->execute();
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0
You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).
Like this $lid = $conn->lastInsertId();
Please check out the docs https://www.php.net/manual/en/language.oop5.basic.php
In my database there is a table, that contains only one row: id. It's something like a facade for another table:
Now I want to add an entry into whatever_set, in order to be able to create entries in the dependent tables. In SQL I would write:
INSERT INTO whatever_set VALUES ();
But when I try it with Zend\Db
$action = new Insert(whatever_set');
$data = [];
$action->values($data);
$sql = new Sql($this->dbAdapter);
$statement = $sql->prepareStatementForSqlObject($action);
$result = $statement->execute();
I get an exception:
values or select should be present
There are some possible workarounds (see below). But is there though a "Zend way" to save empty with no VALUES? How to do this?
Workaround 1
Custom Insert class.
Workaround 2
Raw SQL like
$sql = 'INSERT INTO whatever_set VALUES ();';
$result = $this->dbAdapter->getDriver()->getConnection()->execute($sql);
I'm new to php and I've searched for the past hour and read all the documentation I could find and nothing is helping. I have a table that has a bunch of rows of data. I'm trying to pick one column from the whole table and add them all together. Here is what I got. All this tells me is how many rows there are that match my query, not the total sum of column I want. Any help is appreciated.
$res1 = $db->prepare('SELECT sum(distance) FROM trip_logs WHERE user_id = '. $user_id .' AND status = "2"');
$res1->execute();
$sum_miles = 0;
while($row1 = $res1->fetch(PDO::FETCH_ASSOC)) {
$sum_miles += $row1['distance'];
}
echo $sum_miles;
You're only returning one row in this instance. Modify your summed column to have an alias:
SELECT SUM(distance) AS totDistance FROM trip_logs ....
Now you can can fetch the row -
$row = $res1->fetch(PDO::FETCH_ASSOC);
echo $row['totDistance'];
No need to loop.
You can use SUM() without explicitely grouping your rows because if you use a group function in a statement containing no GROUP BY clause, it is equivalent to grouping on all rows.
If however you want to use the SUM() function for something slightly more complicated you have to group your rows so that the sum can operate on what you want.
If you want to get multiple sums in a single statement, for example to get the distance for all users at once, you need to group the rows explicitely:
$res1 = $db->prepare("
SELECT
SUM(distance) AS distance,
user_id
FROM trip_logs WHERE status = '2'
GROUP BY user_id
");
$res1->execute();
while ($row = $res1->fetch(PDO::FETCH_ASSOC))
{
echo "user $row[user_id] has runned $row[distance] km.\n";
}
This will return the sum of distances by user, not for all users at once.
Try this if you are using a Class :
class Sample_class{
private $db;
public function __construct($database) {
$this->db = $database;
}
public function GetDistant($user_id,$status) {
$query = $this->db->prepare("SELECT sum(distance) FROM trip_logs WHERE user_id =? AND status =?");
$query->bindValue(1, $user_id);
$query->bindValue(2, $status);
try{ $query->execute();
$rows = $query->fetch();
return $rows[0];
} catch (PDOException $e){die($e->getMessage());}
}
}
$dist = new Sample_class($db);
$user_id = 10;
$status = 2;
echo $dist->GetDistant($user_id,$status);
My mysql query is working fine
INSERT INTO donor_location (pc_id)
SELECT id
FROM pc
WHERE postcode= ?
i.e gets the postcode id from a postcode table then inserts that id into donor_location table.
I am using mysqli and prepared statements
without the select part it would be quite easy - something like
$stmt = $mysqli->prepare("INSERT INTO donor_charity(
id) values (?)") ;
however I am completely lost about how to incorporate the select
What you do is almost the same, just changing the query bit.
To select all records from charity_donor where the id is 25, you would do the follwing query:
SELECT *
FROM donor_charity
WHERE id = 25
Now to query this, first you have to prepare it:
$stmt = $mysqli->prepare("
SELECT *
FROM donor_charity
WHERE id = ?
");
Now to loop over the results, you must bind the param, and execute the query.
$stmt->bind_param('d', 25 ); // First param means the type of the value you're
passing. In this example, d for digit.
$stmt->execute();
Then you setup an array to hold the data returned from the query,
$row = array();
stmt_bind_assoc($stmt, $row);
And now to loop over the returned data.
while ( $stmt->fetch () ) {
print_r($row); // Should now contain the column.
}
For documentation, see:
Prepare: http://www.php.net/manual/en/mysqli.prepare.php
Bind param: http://www.php.net/manual/en/mysqli-stmt.bind-param.php
Execute: http://www.php.net/manual/en/mysqli-stmt.execute.php
Fetch: http://www.php.net/manual/en/mysqli-stmt.fetch.php
You need to use Bind_param after Prepare statement.
$sql = "INSERT INTO donor_charity(
id) values (?)
";
/* create a prepared statement */
if (!$stmt = $db->prepare($sql)) {
echo 'Database prepare error';
exit;
}
/* bind parameters for markers */
$stmt->bind_param('ssssss', $id);
$id = '123456';
/* execute query */
$stmt->execute();
Hope this post helps, it's so simple.
http://www.java2s.com/Code/Java/Database-SQL-JDBC/InsertRecordsUsingPreparedStatement.htm
I am having an issue with inserting an array of information into a mysql database. Basically I built a sortable gallery similar to Facebook's photo albums that can be arranged by moving the div to a new spot with jquery's sortable function.
I am using Ajax to call a php file which will inser the new order of the div's into the DB. The information is being passed correctly, it is just not being inserted correctly.
The error I am receiving is:
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 'Array' at line 1
The Php code is:
foreach ($_GET['listItem'] as $position => $item) {
if ($item >= 1) {
$sql[] = "UPDATE table SET order = '{$position}' WHERE id = '{$item}'";
mysql_query($sql) or die(mysql_error());
}
}
If I remove the mysql_query function and just do a print_r, I get:
Array
(
[0] => UPDATE table SET order = '0' WHERE id = '2'
[1] => UPDATE table SET order = '1' WHERE id = '4'
[2] => UPDATE table SET order = '2' WHERE id = '3'
[3] => UPDATE table SET order = '3' WHERE id = '1'
[4] => UPDATE table SET order = '4' WHERE id = '5'
[5] => UPDATE table SET order = '5' WHERE id = '6'
)
This is the first time I have tried to do something like this. Any help would be great.
Thank you in advance for the help!
In mysql_query($sql) $sql is an array, therefore it's value is simply Array. When you assign $sql[] = "UPDATE table SET order = '{$position}' WHERE id = '{$item}'"; simply make this line $sql = "UPDATE table SET order = '{$position}' WHERE id = '{$item}'";. That should solve your problem.
EDIT:
You can leave the [] and simply remove the mysql_query from where it is. After your foreach list item, add this:
foreach($sql as $query) {
mysql_query($query);
}
Sounds like there is some confusion about what the [] operator does. You use [] when you want to append an element to the end of an existing array.
For example:
$sql = array();
$sql[] = 'UPDATE table SET order = "0" WHERE id = "2"';
mysql_query($sql); // this will produce the error you are seeing
Versus:
$sql = 'UPDATE table SET order = "0" WHERE id = "2"';
mysql_query($sql); // this will work
You should rewrite your code as such:
foreach ($_GET['listItem'] as $position => $item) {
if ($item >= 1) {
$sql = "UPDATE table SET order = '{$position}' WHERE id = '{$item}'";
mysql_query($sql) or die(mysql_error());
}
}
That will do what you are intending. However, this is still not a good idea, since you are passing untrusted $_GET data directly to the database. I could, for example, call your script with a string like:
http://yoursite.com/yourscript.php?listItem=1'%3B%20DROP%20TABLE%20yourtable%3B
Since the value of listItem is going directly to the database -- and the $item >= 1 check is insufficient, since PHP will evaluate a string as an integer if it begins with numeric data -- all I have to do is add a single quote to terminate the previous query, and I am then free to inject whatever SQL command I'd like; this is a basic SQL injection attack. Whenever you write database-touching code, you should cleanse any input that might be going to the database. A final version of your code might look like:
foreach ($_GET['listItem'] as $position => $item) {
if ($item >= 1) { // this check may or may not be needed depending on its purpose
$sql = 'UPDATE table SET order = "' . mysql_real_escape_string($position) . '" WHERE id = "' . mysql_real_escape_string($item) . '"';
mysql_query($sql) or die(mysql_error());
}
}
There are other ways to cleanse input data as well, that is just one of them. Hope that helps.