Inserting/updating data into MySql database using php - php

I am trying to insert/update the MySql database depending on whether a post already exists on the database (I am checking this with a unique user_id). The following works:
$select_query = "SELECT * ";
$select_query .= "FROM test ";
$select_query .= "WHERE user_id = '$user_id'";
$check_user_id = mysqli_query($connection, $select_query);
$query = "INSERT INTO test (";
$query .= " user_id, name, message";
$query .= ") VALUES (";
$query .= " '{$user_id}', '{$name}', '{$message}'";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result) {
echo "Success!";
} else {
die("Database query failed. " . mysqli_error($connection));
}
However, when I use the following code with an if/else statement, it does not work anymore, although the console reports "Success!" (meaning $result has a value). Any help would be greatly appreciated. Thanks.
$select_query = "SELECT * ";
$select_query .= "FROM test ";
$select_query .= "WHERE user_id = '$user_id'";
$check_user_id = mysqli_query($connection, $select_query);
if (!$check_user_id) {
$query = "INSERT INTO test (";
$query .= " user_id, name, message";
$query .= ") VALUES (";
$query .= " '{$user_id}', '{$name}', '{$message}'";
$query .= ")";
} else {
$query = "UPDATE test SET ";
$query .= "name = '{$name}', ";
$query .= "message = '{$message}' ";
$query .= "WHERE user_id = '{$user_id}'";
}
$result = mysqli_query($connection, $query);
if ($result) {
echo "Success!";
} else {
die("Database query failed. " . mysqli_error($connection));
}

As i understand your code. you are trying to check if the user_id is existing in your database..
i made a simple code and i think its works for me..
$select_query = mysql_query("SELECT * FROM test WHERE user_id = '$user_id'") or die (mysql_error());
$result = mysql_num_rows($select_query);
if(!$result){
$query = mysql_query("INSERT INTO test (user_id, name, message) VALUES ('$user_id', '$name', '$message')");
if($query){
echo "Success!";
}
else
{
die (mysql_error());
}
}
else{
$query2 = mysql_query("UPDATE test SET name='$name', message='$message' WHERE user_id = '$user_id'")
}

mysql_query returns the operation identifier, not the actual result. This is why $check_user_id is always true, so you are always trying to update (even not existing!) rows.
you have to "read" the result ofmysql_queryby for example using
$check_user_id = mysql_num_rows( mysql_query($connection, $select_query) );
now it returns 0 (false) iff there were no results for q $select_query

This statement is giving you a resource to the result
$check_user_id = mysqli_query($connection, $select_query);
next you are checking for if(!$check_user_id) : this condition evaluates to false because of the negation !. Thus your condition goes to the else part and and never enters the if.
The $result always has value because you are calling it towards the end of the script.

Since you previously know the user_id, and assuming that is a primary key in the table, you could use "ON DUPLICATE KEY UPDATE" clause:
$query = mysql_query("INSERT INTO test (user_id, name, message)
VALUES ('$user_id', '$name', '$message')
ON DUPLICATE KEY
UPDATE name='$name', message='$message';
");
Same result with only one query.
Ref: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

Use Code for data inserting in mysql.
$query = mysql_query("INSERT INTO test set user_id = '$user_id', name = '$name', message = '$message'");
if($query){
echo "Success!";
}

Related

Dynamic SQL statement based on foreach

How would I get this to work, because I am just getting errors right now.
$_GET['providers'] is an array of DB column names, which I am checking if = 1 in the below query.
foreach ($_GET['providers'] as $providers) {
$statement = "AND ".$providers."= '1' ";
}
$sql = "select * from users where user_id ='1' ".$statement." ";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
if(isset($row['user_id'])){
echo "It worked";
}
You should use a whitelist to check if the $providers are known column names. You then should concatenate the $statement, otherwise you overwrite that variable on every iteration.
$statement = '';
$columns = array('known', 'columns', 'go', 'here');
foreach ($_GET['providers'] as $providers) {
if(in_array($providers, $columns)) {
$statement .= " AND $providers = 1 ";
}
}
$sql = "select user_id from users where user_id =1 $statement limit 1";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
if(isset($row['user_id'])){
echo "It worked";
}
You also shouldn't use * unless you really want every column. If you just want to see if a row is returned you also can use limit 1 because you don't care about other rows.
You are overwriting $statement every time the loop is running.
$statement = "";
foreach ($_GET['providers'] as $providers) {
$statement .= "AND ".$providers."= '1' "; // note the ".=" to append
}
$sql = "select * from users where user_id ='1' ".$statement." ";
// to debug: echo "Query :: $sql";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
if(isset($row['user_id'])){
echo "It worked";
}

How to get result from query and insert the results in other table?

I did query to the database where I need the results from it and then store it in a variable. Then I will pass the variable to the INSERT INTO statement but for some reason my code does not work. This is my code/
$query = "SELECT * from animals where old= 1 AND user_id=".$_SESSION['user_id'];
$result = mysqli_query(mysqli_connect("","","", ""), $query);
while ($row = mysqli_fetch_array($result))
{
$variable[] = $row['number'];
}
//now I will pass the $variable to the INSERT INTO statement
if(isset($_POST['submit_d']))
{
foreach($variable as $var)
{
$query="INSERT INTO selectedanimals(number) VALUES ({$var},2)";
mysqli_query($con, $query) or die (mysql_error());
}
?>
<script>
alert("Animal added.");
self.location="chooseAnimals.php";
</script>
<?php
}
?>
You can use INSERT INTO ... SELECT for this purpose in a single query:
INSERT INTO selectedanimals (number)
SELECT number
FROM animals
WHERE old = 1 AND user_id = some_id
PHP code:
$query = "INSERT INTO selectedanimals (number) ";
$query.= "SELECT number FROM animals WHERE old = 1 AND user_id = ".$_SESSION['user_id'];
mysqli_query($con, $query) or die (mysql_error());

Isolating the fields that were updated

I'm trying to check whether an existing field have been changed and identify it so i can later add it into a changes table. Any idea on how to do so?
if (isset($_POST['submit']))
{
$sql = "SHOW COLUMNS FROM Employees";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)){
$tempname = $row['Field'];
$sql2 = "UPDATE Employees SET ".$row['Field']."= '$_POST[$tempname]' WHERE AFNumber='".$_GET["af"]."'";
$result2 = mysqli_query($con,$sql2);
if ($con->query($sql2) === TRUE) {
} else {
echo "Error: " . $sql2 . "<br>" . $con->error;
echo '<script>swal("Error", "Something went wrong '.$con->error.'", "error");</script>';
}
First of all I think you have missed a ".$var." in this line:
$sql2 = "UPDATE Employees SET ".$row['Field']."= '$_POST[$tempname]' WHERE AFNumber='".$_GET["af"]."'";
it should be like this:
$sql2 = "UPDATE Employees SET ".$row['Field']."= '".$_POST[$tempname]."' WHERE AFNumber='".$_GET["af"]."'";
you could do a select query first to diff against the data you want to update
// get the rows that will be changed
$sqlOldData = "SELECT * FROM Employees WHERE AFNumber='".$_GET["af"]."' AND (".$row['Field']." NOT LIKE '".$_POST[$tempname]."')";
and then update the table.
Q: But one question, as for integrating it in the code, any help please, i'm just starting in this area:
$sql3 = "INSERT INTO Changes (Table, AFNumber, Attribute,DateChanged,HRUser,OldValue,NewValue) VALUES ('Employees', '".$_GET["af"]."', '".$row["Field"]."', '".date('dd/m/Y HH:mm:ss')."', '$login_session', '', '$_POST[$tempname]')";
NOTE: First of all you missed again some string breakouts:
'$login_session' --> '".$login_session."'
'$_POST[$tempname]' --> '".$_POST[$tempname]."'
so you get:
$sql3 = "INSERT INTO Changes (Table, AFNumber, Attribute,DateChanged,HRUser,OldValue,NewValue) VALUES ('Employees', '".$_GET["af"]."', '".$row["Field"]."', '".date('dd/m/Y HH:mm:ss')."', '".$login_session."', '', '".$_POST[$tempname]."')";
A: adoption $resultOldData is the result of $sqlOldData
this should work:
while($rowOldData = mysqli_fetch_array($result))
{
$sql3 = "INSERT INTO Changes (Table, AFNumber, Attribute,DateChanged,HRUser,OldValue,NewValue) VALUES ('Employees', '".$_GET["af"]."', '".$row["Field"]."', '".date('dd/m/Y HH:mm:ss')."', '".$login_session."', '".$rowOldData[$row['Field']]."', '".$_POST[$tempname]."')";
mysqli_query($con,$sql3);
}

Sending information from a newly created record to a different MySQL table

I'm making a form that submits a story into a MySQL table called 'work'. I want to later take the id of the newly created record and put the information into a different table.
But when I submit the story, it says:
$workid is undefined.
I can't see the problem though because I believe I've defined it?
<?php
if (!empty($_POST) && !empty($_POST['title']) && !empty($_POST['story']) && !empty($_POST['genre']) && !empty($_POST['rating'])) {
$title = strip_tags($_POST['title']);
$story = strip_tags($_POST['story']);
$title = mysqli_real_escape_string($db, $title);
$story = mysqli_real_escape_string($db, $story);
$genre = $_POST['genre'];
$rating = $_POST['rating'];
$query = "SELECT COUNT(*) AS count FROM works WHERE Title = '".$title."'";
$result = $db->query($query);
$data = $result->fetch_assoc();
if ($data['count'] > 0) {
echo "<p>Story already exists!</p>";
} else {
$query = "INSERT INTO works (author_id, login_id, Title, Story, Genre, Rating) VALUES ('".$userid."','".$authorid."','".$title."','".$story."','".$genre."','".$rating."')";
$query = "SELECT `id` FROM `works` WHERE `Title` = '".$title."'";
if ($result = $db->query($query)) {
while ($row = $result->fetch_assoc())
$workid = $row["id"]; //workid is written here but still considered undefined
}
$query = "INSERT INTO `author_work` (`author_id`) VALUES ('".$authorid."')";
$result = $db->query($query);
$query = "INSERT INTO `author_work` (`work_id`) VALUES ('".$workid."')";
$result = $db->query($query);
$query = "INSERT INTO `login_work` (`work_id`) VALUES ('".$workid."')";
$result = $db->query($query);
$query = "INSERT INTO `login_work` (`login_id`) VALUES ('".$userid."')";
$result = $db->query($query);
if ($result) {
echo "<p>Story submitted!</p>";
} else {
echo "SQL Error: " . $db->error;
}
}
}
?>
You never did a $db->query() on your INSERT INTO... query string, so it was never inserted, and was overwritten by your SELECT id ... query.
$query = "INSERT INTO works (author_id, login_id, Title, Story, Genre, Rating) VALUES ('".$userid."','".$authorid."','".$title."','".$story."','".$genre."','".$rating."')";
$db->query($query); // Missing this $db->query()
$query="SELECT `id` FROM `works` WHERE `Title` = '".$title."'";
if ($result = $db->query($query)) {
while ($row= $result->fetch_assoc())
$workid = $row["id"];}
Your $workid might not be initialized, depending on your condition and the result of your SQL query: so try to avoid next operations that will causes warnings/errors by using continue or else

convert | separated values into new table using PHP

Edit: I forgot to add the explode part that I'm having the issues with. I need the query result exploded.
I have been messing with this for a while and have a workable procedure in mysql, however I want to accomplish this as part of a larger script. I have a table filled with IDs and several columns of data with "|" separated values. How can I use or edit the below PHP to query and insert normalized results into a new table?
If I run this with an actual string: "40|180|408|360|40|166|80|59"; It will insert values (not the ID, which I also need) but when I try to pass in query results, I get "Array to string conversion" errors. Any guidance would be appreciated.
$query = "Select id, imageSize from T1";
$result = mysqli_query($conn, $query);
$myArray = explode('|', $result);
foreach($myArray as $value) {
$sql = "INSERT INTO testExplode VALUES ($value)";
$result = mysqli_query($conn, $sql);
}
If you want to insert all of your results then:
$query = "Select id, imageSize from T1";
$myArray = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($myArray)) {
$sql = "INSERT INTO testExplode VALUES (" . mysqli_real_escape_string($conn, $row['imageSize']) . ")";
mysqli_query($conn, $sql);
}
//If just only one:
$query = "Select id, imageSize from T1";
$myArray = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($myArray);
$sql = "INSERT INTO testExplode VALUES (" . mysqli_real_escape_string($conn, $row['imageSize']) . ")";
mysqli_query($conn, $sql);
NOTE:
Avoid sql injecions by escaping your variables in your querys.
EDIT:
Based on the OP comment.
$query = "Select id, imageSize from T1";
$myArray = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($myArray)) {
$values = explode('|', $row['imageSize']);
foreach ($values as $value) {
$sql = "INSERT INTO testExplode VALUES (" . mysqli_real_escape_string($conn, $value) . ")";
mysqli_query($conn, $sql);
}
}

Categories