A select that is not working - php

I have a select that doesn't work.
$person = mysql_query ("Select personID from persons order by personID desc Limit 0,1");
$query_string = 'INSERT INTO topics (topic,
description,
abstract,
personID)
VALUES (?, ?, ?, ?)';
$query = $db->prepare($query_string);
$query->execute(array($_POST['topic'],
$_POST['description'],
$_POST['abstract'],
$person));
I dont understand where is the problem

$person is a mysql result, not any kind of value.
Try this:
list($person) = mysql_fetch_row(mysql_query("select personID from ....."));

Here is the problem...
$person = mysql_query ("Select personID from persons order by personID desc Limit 0,1");
Do this...
$result = mysql_query ("Select personID from persons order by personID desc Limit 0,1");
$row = mysql_fetch_array($result);
$person = $row['personID'];

you are mixing to fetch mysql inside mysqli try this.
$person = $db->prepare("Select personID from persons order by personID desc Limit 0,1");
$person->execute();
$person->store_result();
$person->bind_result( $personID ) ; // to bind the result as variable to use it later
$person->fetch();
$query_string = 'INSERT INTO topics (topic,
description,
abstract,
personID)
VALUES (?, ?, ?, ?)';
$query = $db->prepare($query_string);
$query->execute(array($_POST['topic'],
$_POST['description'],
$_POST['abstract'],
$personID));

$dbh = new PDO('mysql:host='.$server.';dbname='.$db, $user, $pass);
$st=$dbh->prepare('Select personID from persons order by personID desc Limit 0,1');
$st->execute();
$result=$st->fetchAll();
//FOR TEST PURPOSE TO MAKE IT EASY.
echo "<pre>";
print_r($result);
echo "</pre>";
//END TEST
echo $result[0]['personID'];
Try this PDO code to select and use data.PDO is a prefererred way. and also instead of mysql use mysqli.
we are unclear about your concern. it would be better if you copy paste the error message or make us clear by editing you post, saying what actually you want and what you are unable to do. hope my help works!!

Related

How can I use several SQL SELECT queries as WHERE clauses in php?

$sql = "INSERT into x (y,z,t)
VALUES ((SELECT userID FROM users WHERE username ='".$usersql."'),"
."'"."(SELECT itemID from items WHERE category ='".$category."'),"
."'".$amountdays."')";
Thank you for your time.
You should use PDO or mysqli with prepared statements. Then you can define variables for your values and set them after the query. That makes it more readable and you prevent sql injections in your code.
https://www.php.net/manual/de/pdo.prepared-statements.php
$stmt = $dbh->prepare("INSERT into x (y,z,t)
VALUES (
SELECT userID FROM users WHERE username = :username,
SELECT itemID FROM items WHERE category = :category,
:amountdays
)";
$stmt->bindParam(':username', $username);
$stmt->bindParam(':category', $category);
$stmt->bindParam(':amountdays', $amountdays);
Something like that.
A little bit of formatting will go a long way:
$sql = "INSERT into x
(
y,
z,
t
) VALUES (
(SELECT userID FROM users WHERE username = ?),
(SELECT itemID from items WHERE category = ?),
?
);
";

How do i insert the value of the primary key into a insert query

How do I retrieve the value of the primary key in customer_information table, such that I could input the value into the INSERT statement to store data into my customer_payment_information table?
I thought of calling the value of the primary key and store it in a variable, such that I could input the variable into my INSERT statement to store data for my customer_payment_information table.
Unfortunately, nothing is being stored in my database.
This is my code:
$sql = "SELECT customer_id FROM customer_information ORDER BY customer_id DESC LIMIT 1";
if ($conn->query($sql)){
$compile = $conn->prepare("INSERT INTO customer_payment_information (customer_id, fullName, creditcardNumber, expiry, ccv) VALUES (?, ?, ?, ?, ?)");
$compile->bind_param("issss", $sql, $ccname, $ccnumber, $expdate, $ccvnumber);
$compile->execute();
$compile->close();
$conn->close();
} else {
$errorMsg = "Connection failed: " . $conn->connect_error;
}
The primary key of TABLE 1 has auto_increment, hence the SQL query
"SELECT customer_id FROM customer_information ORDER BY customer_id DESC LIMIT 1"
TABLE 1:
TABLE 1 FORMAT
TABLE 2:TABLE 2 FORMAT
You need to execute your inital select statement and get the result. Something like this should do it for you.
$sql = "SELECT customer_id FROM customer_information ORDER BY customer_id DESC LIMIT 1";
$customerQuery = $conn->query($sql);
$customerResult = $customerQuery->fetch_assoc();
$customerId = $customerResult['customer_id'];
$compile
= $conn->prepare("INSERT INTO customer_payment_information (customer_id, fullName, creditcardNumber, expiry, ccv) VALUES (?, ?, ?, ?, ?)");
$compile->bind_param("issss", $customerId, $ccname, $ccnumber, $expdate, $ccvnumber);
$compile->execute();
$compile->close();
$conn->close();
You may want to consider something like SELECT LAST_INSERT_ID() after insertiing a record to get it's id for further use.

UPDATE table record instead of adding a new record MySQL

Ok .. Here is the thing. I want to list users logged on and change their status when logged out. This works perfect. I created a table for that called tblaudit_users. The existing users I SELECT from a tbl_users table.
What I want, is that if an user already exists in the tblaudit_users table it will UPDATE the LastTimeSeen time with NOW(). But instead of updating that record, it creates a new record. This way the table will grow and grow and I want to avoid that. The code I use for this looks like:
+++++++++++++++++++
$ipaddress = $_SERVER['REMOTE_ADDR'];
if(isset($_SESSION['id'])){
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
$achternaam = $_SESSION['achternaam'];
$district = $_SESSION['district'];
$gemeente = $_SESSION['gemeente'];
$query = $db->prepare("SELECT * FROM tblaudit_users WHERE username = '{$username}' AND active = '1' LIMIT 1");
$query->execute();
foreach($query->fetchAll(PDO::FETCH_OBJ) as $value){
$duplicate = $value->username;
}
if($duplicate != 1){
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district, gemeente, ipaddress, LastTimeSeen, status)
VALUES ('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW(), '1')
");
$insert->execute();
} elseif($duplicate = 1){
$update = $db->prepare("UPDATE tblaudit_users SET LastTimeSeen = NOW(),status = '1' WHERE username = '{$username}'");
$update->execute();
} else {
header('Location: index.php');
die();
}
}
I am lost and searched many websites/pages to solve this so hopefully someone here can help me? Thanks in advance !!
UPDATE:
I've tried the below with no result.
+++++
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district, gemeente, ipaddress, LastTimeSeen, status)
VALUES ('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW(), '1')
ON DUPLICATE KEY UPDATE set LastTimeSeen = NOW(), status = '1'
");
$insert->execute();
Ok. I altered my query and code a little:
$query = $db->prepare("SELECT * FROM tblaudit_users WHERE username = '{$username}' LIMIT 1");
$query->execute();
if($query){
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district, gemeente, ipaddress, LastTimeSeen, status)
VALUES ('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW(), '1')
ON DUPLICATE KEY UPDATE set LastTimeSeen = NOW(), status = '1'
");
$insert->execute();
} else {
header('Location: index.php');
die();
}
}
I also added a UNIQUE key called pid (primary id). Still not working.
Base on http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html, don't use 'set' in update syntax
example from the page:
INSERT INTO table (a,b,c) VALUES (4,5,6) ON DUPLICATE KEY UPDATE c=9;
Several issues:
You test on $query, but that is your statement object, which also will be valid even if you have no records returned from the select statement;
There can be issues accessing a second prepared statement before making sure the previous one is closed or at least has all its records fetched;
There is a syntax error in the insert statement (set should not be there);
For the insert ... on duplicate key update to work, the values you provide must include the unique key;
SQL injection vulnerability;
Unnecessary split of select and insert: this can be done in one statement
You can write your test using num_rows(). To get a correct count call store_result(). Also it is good practice to close a statement before issuing the next one:
$query = $db->prepare("SELECT * FROM tblaudit_users
WHERE username = '{$username}' LIMIT 1");
$query->execute();
$query->store_result();
if($query->num_rows()){
$query->close();
// etc...
However, this whole query is unnecessary when you do insert ... on duplicate key update: there is no need to first check with a select whether that user actually exists. That is all done by the insert ... on duplicate key update statement.
Error in INSERT
The syntax for ON DUPLICATE KEY UPDATE should not have the word SET following it.
Prevent SQL Injection
Although you use prepared statements (good!), you still inject strings into your SQL statements (bad!). One of the advantages of prepared statements is that you can use arguments to your query without actually injecting strings into the SQL string, using bind_param():
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district,
gemeente, ipaddress, LastTimeSeen, status)
VALUES (?, ?, ?, ?, ?, ?, NOW(), '1')
ON DUPLICATE KEY UPDATE LastTimeSeen = NOW(), status = '1'
");
$insert->bind_param("ssssss", $userId, $username, $achternaam,
$district, $gemeente, $ipaddress);
$insert->execute();
This way you avoid SQL injection.
Make sure that user_id has a unique constraint in the tblaudit_users. It does not help to have another (auto_increment) field as primary key. It must be one of the fields you are inserting values for.
The above code no longer uses $query. You don't need it.
I found the issue
if(isset($_SESSION['id'])){
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
$achternaam = $_SESSION['achternaam'];
$district = $_SESSION['district'];
$gemeente = $_SESSION['gemeente'];
$query = $db->prepare("SELECT * FROM tblaudit_users WHERE user_id = '{$userId}' LIMIT 1");
$query->execute();
if($query->rowcount()<1){
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district, gemeente, ipaddress, LastTimeSeen, status)
VALUES ('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW(), '1')
");
$insert->execute();
} elseif($query->rowcount()>0) {
$update = $db->prepare("UPDATE tblaudit_users SET LastTimeSeen = NOW(),status = '1' WHERE user_id = '{$userId}'");
$update->execute();
} else {
header('Location: index.php');
die();
}
}
Instead of using $username in my query, I choose $userId and it works.

DropDown Isset IF statement to move entire record MySQL

I'm new to php. I have a dropdown option. I want to put an if statement that if one of the options is selected e.g. 'Completed' then I would like it to get the entire record from the MySQL table and move it to another table with the same table structure.
This is what i have so far:
<?php
if( $_GET['status'] = 'Completed' ):
$stmt = $con->prepare("INSERT INTO second_table select * from first_table where id = id;
status = ?,
day_id = ?,
eta = ?,
c_notes = ?
WHERE booking_id = ?");
$stmt->bind_param('sissi',
$_GET['status'],
$_GET['day_id'],
$_GET['eta'],
$_GET['notes'],
$_GET['id']
);
$stmt->execute();
$stmt->close();
?>
If the two tables have the same structures I think your query should be
$stmt = $con->prepare("INSERT INTO second_table VALUES (SELECT * FROM first_table WHERE id = ?");
$stmt->bind_param('i', $_GET['id'] );
Let me know if this didn't work.

php mysqli prepared statement

Hey, I have a quick one. Is there any way to include a variable into a prepared query? example:
$sql = "SELECT id, title, author, LEFT(description, 40) AS excerpt,
image_small, image_med, date
FROM posts
ORDER BY id DESC
LIMIT $start, $postsPerPage";
$result = $connect->prepare($sql) or die ('error');
$result->execute();
$result->bind_result($id, $title, $author, $excerpt, $image_small, $image_med, $date);
Thanks!
you want the following:
$start = 1; $postsPerPage = 1;
$sql = "SELECT id, title, author, LEFT(description, 40) AS excerpt,
image_small, image_med, date
FROM posts
ORDER BY id DESC
LIMIT ?, ?";
$stmt = $connect->prepare($sql) or die ('error');
$stmt->bind_param('ii', $start, $postsPerPage);
$stmt->execute();
$stmt->bind_result($id, $title, $author, $excerpt, $image_small, $image_med, $date);
while($stmt->fetch()) {
printf('<h1>%s</h1><p>%s <small> by %s on %s</small></p>',
htmlspecialchars($title),
htmlspecialchars($excerpt),
htmlspecialchars($author),
htmlspecialchars($date)
);
}
this binds both question marks to integer (i) values of $start and $postsPerPage. do NOT use variables directly in prepared statements, because that would defeat the whole purpose of prepared statements (apart from eliminating parsing time)
Use question marks as placeholders in the SQL where you want the value of the variable to be.
Use mysqli_stmt::bind_param to bind values to the placeholders.
If I'm not mistaken you have to use bindParam and replace the variables in your query with a question mark
$sql = "SELECT id, title, author, LEFT(description, 40) AS excerpt,
image_small, image_med, date
FROM posts
ORDER BY id DESC
LIMIT ?, ?";
$result = $connect->prepare($sql) or die ('error');
$result->bindParam(1, $start);
$result->bindParam(2, $postsPerPage);
you can find more examples at http://php.net/manual/en/pdo.prepared-statements.php

Categories