Using variables in MySQL UPDATE - (PHP/MySQL) - php

I am trying to use variables in mysql update code, but i got the else {echo error message}.
$overwriteName = "UPDATE name SET name = '{$steamprofile['personaname']}' WHERE steamid = '{$steamprofile['steamid']}';";
if ($db->query($overwriteName) === TRUE) {
echo "success";
} else {
echo "error";
}

An easy way of doing this is using prepared statement:
(it's also more secure than using query, see the link for more information)
if($stmt = $db->prepare('UPDATE name SET name = ? WHERE steamid = ?')){ // prepare the query
$stmt->bind_param('ss',$steamprofile['personaname'],$steamprofile['steamid']); // bind your parameters (as many s as there are variables)
$stmt->execute();
// then your code
}

PHP doesn't substitute the value of a variable if you enclose it between simple quotes '$variable'.
In the query declaration, enclose $steamprofile['personaname'] and $steamprofile['steamid'] like this:
$overwriteName = "UPDATE name SET name = " . "$steamprofile['personaname']" . " WHERE steamid = " . "$steamprofile['steamid']" . ";";
Or don't enclose them at all:
$overwriteName = "UPDATE name SET name = " . $steamprofile['personaname'] . " WHERE steamid = " . $steamprofile['steamid'] . ";";

Related

How do I get all values to echo with mysqli_fetch_assoc?

I'm pretty new to php, so don't really know how to do much, but from what I've looked up, this should echo all values from the two fields.
<?php
$con = mysqli_connect('localhost', 'root', 'root', 'unityaccess');
if(mysqli_connect_errno())
{
echo "1: Connection failed"; //error code 1 = connection failed
exit();
}
$username = $_POST["name"];
$idcheckquery = "SELECT id FROM users WHERE username = '" . $username . "';";
$idcheck = mysqli_query($con, $idcheckquery) or die("7: ID check query failed"); //error code 8 = couldn't get user's id
$existingid = mysqli_fetch_assoc($idcheck);
$userid = $existingid["id"];
$itemfindquery = "SELECT itemid, equipped FROM inventory WHERE userid = '" . $userid ."';";
$itemfind = mysqli_query($con, $itemfindquery) or die("9: Couldn't find items");
while($row = $mysqli_fetch_assoc($itemfind)){
echo $row["itemid"] . ", " . $row["equipped"] . " ";
}
?>
I expect this to, when it is called in unity, to print a list of all the values in each list, but instead it doesn't echo anything.
The mysqli_fetch_assoc() function is being used as a variable ($). Just remove the dollar sign and it will work.
while($row = mysqli_fetch_assoc($itemfind)){
echo $row["itemid"] . ", " . $row["equipped"] . " ";
}
Also, try to use prepared statements to fight against SQL injections.

Cannot update the row in mysql via php

I tried to update a row in table showtable
Bugupdate
By using the php code below, binding a bugID to a SQL UPDATE statement to update the row I want to but it doesn't seem to work, is it the problem lie in my SQL statement ?
$id = $_GET['update'];
$games = htmlentities($_POST['games']);
$version = htmlentities($_POST['version']);
$platform = htmlentities($_POST['platform']);
$frequency = htmlentities($_POST['frequency']);
$proposal = htmlentities($_POST['proposal']);
$SQLstring2 = "UPDATE " .$TableName. " SET Game=?,Version=?,Platform=?,Frequency=?,Proposed solution=? WHERE BugID= " .$id;
if ($stmt = mysqli_prepare($DBconnect, $SQLstring2)) {
mysqli_stmt_bind_param($stmt,'sssss', $games, $version, $platform, $frequency, $proposal);
$QueryResult2 = mysqli_stmt_execute($stmt);
if ($QueryResult2 === FALSE) {
echo "<p>Unable to execute the query.</p>"
. "<p>Error code "
. mysqli_errno($DBconnect)
. ": "
. mysqli_error($DBconnect)
. "</p>";
} else {
echo "<h1> Thank you for your contribution";
}
mysqli_stmt_close($stmt);
}
mysqli_close($DBconnect);
Try to rename Proposed solution column to Proposed_solution and adapte the sql query like this :
$SQLstring2 = "UPDATE " .$TableName. " SET Game=?,Version=?, Platform=?, Frequency=?, Proposed_solution=? WHERE BugID= " .$id;

Checking Table exists before inserting php sql

I am trying to check if a table exists before entering the data into it. I am trying mysql_query and getting errors that I should be using mysqli, but it does not seem to be working for me.
This is my code so far:
$AllData = $_POST["table"];
foreach ($AllData as $sigleData) {
$table = $sigleData['name'];
$columns = implode(", ", $sigleData['columns']);
$columnData = implode(" ',' ", $sigleData['data']);
// Insert into database tuple data
$sqlQuery = "INSERT INTO " . $table . " ( " . $columns . ") VALUES( '" . $columnData . "')";
if ($dbConnectionT->query($sqlQuery) == TRUE) {
echo "database updated";
echo "</br>";
}
}
Try this way to check table exists or not using this custom function and then insert row to your db.
function check_table_exist($table){
global $dbConnection; // see here global connection variable
$sql = "SHOW tables LIKE '".$table."'";
$res = $dbConnection->query($sql);
return ($res->num_rows > 0);
}
#check first table exists or not
if(check_table_exists($table)){
$sqlQuery = "INSERT INTO " . $table . " ( " . $columns . ") VALUES( '" . $columnData . "')";
//do other stuff........
}else{
echo "Table Not Exists";
die('Going Out');
}
Table name is accepted as POST parameter, seriously !! - bad practice.
You can do various check to table existence like
DESC tbl_name;
SHOW CREATE TABLE tbl_name;
SHOW TABLES like 'tbl_name';

How to prevent data being sent to the database if fields are empty?

How would I go about not sending the data to the database if the some of the fields are left empty? Right as of now, if a field is empty on the form, the database is replacing whatever was in the field with blank data
UPDATE: Forgot to mention, it doesn't matter if the some of the fields are left blank, that should be allowed.
My code
<?php
if (isset($_POST['eventname'], $_POST['date'], $_POST['eventvenue'] , $_POST['eventtime'], $_POST['eventcost'])){
$eventname = ($_POST['eventname']);
$eventdate = ($_POST['date']);
$eventtime = ($_POST['eventtime']) . ":00";
$eventvenue = ($_POST['eventvenue']);
$eventcost = ($_POST['eventcost']);
$result = mysql_query("UPDATE event set event_name = '" . $eventname . "', event_date = '" . $eventdate . "', event_time = '" . $eventtime . "', event_venue = '" . $eventvenue ."', event_cost = '" . $eventcost ."'");
}
?>
Try some thing like This
$query= "UPDATE event set ":
If(isset($var1)){
$query.= " var1=".$var1;
}else if (isset($var2)){
$query.= " var2=".$var2;
}
and so forth and then
$result = mysql_query($query);
You can read on PHP's function empty()
empty() on PHP.net
Example usage:
if(empty($eventname))
{
echo "You have not set event name";
} else {
mysqli_query(...);
}
As said on comments, do not use the deprecated mysql_* functions, use either mysqli_* or PDO.
This is an example using prepared statements; it builds the update statement based on whether the field is empty (zero length) or not.
Afterwards, the prepared statement is executed.
$updates = [];
$parameters = [];
if (strlen($_POST['eventname'])) {
$updates[] = 'event_name = ?';
$parameters[] = $_POST['eventname'];
}
// ...
if (strlen($_POST['eventtime'])) {
$updates[] = "event_time = ?";
$parameters[] = $_POST[$field] . ':00';
}
if ($updates) {
$sql = sprintf('UPDATE event SET %s WHERE xxx', join(',', $updates));
$stmt = $db->prepare($sql);
$stmt->execute($parameters);
}

how to update one or more fields ignoring the empty fields into mysql database?

i am seeking help on ignoring null values for updating the mysql database:-
$cst = $_POST['custname'];
$a = $_POST['tel'];
$b = $_POST['fax'];
$c = $_POST['email'];
$sql = mysql_query("UPDATE contacts SET TEL = '$a', FAX = '$b', EMAIL = '$c'
WHERE Cust_Name = '$cst' ");
how do i incorporate an option where the user can only select one or all fields for updation.
i tried using the following code based on responses received but it does the same thing. overwrites the existing data with the blank ones.
$upd = mysql_query("UPDATE custcomm_T SET
Telephone = ".(is_null($a)?'Telephone':"'$a'").",
Fax = ".(is_null($b)?'Fax':"'$b'").",
Mobile = ".(is_null($c)?'Mobile':"'$c'").",
EMail = ".(is_null($d)?'EMail':"'$d'").",
trlicense = ".(is_null($e)?'trlicense':"'$e'").",
trlicexp = ".(is_null($f)?'trlicexp':"'$f'")."
WHERE Cust_Name_VC = '$g' ") or die(mysql_error());
Firstly remember to escape any strings coming to you via POST, GET, or REQUEST (read up on SQL injection attacks if you're unsure why).
Something like this might work:
$semaphore = false;
$query = "UPDATE contacts SET ";
$fields = array('tel','fax','email');
foreach ($fields as $field) {
if (isset($_POST[$field]) and !empty($_POST[$field]) {
$var = mysql_real_escape_string($_POST[$field]);
$query .= uppercase($field) . " = '$var'";
$semaphore = true;
}
}
if ($semaphore) {
$query .= " WHERE Cust_Name = '$cst'";
mysql_query($query);
}
NB: Do not ever simply loop through your $_POST array to create a SQL statement. An opponent can add extra POST fields and possibly cause mischief. Looping through a user input array can also lead to an injection vector: the field names need to be added to the statement, meaning they're a potential vector. Standard injection prevention techniques (prepared statement parameters, driver-provided quoting functions) won't work for identifiers. Instead, use a whitelist of fields to set, and loop over the whitelist or pass the input array through the whitelist.
You need to build your query. Something like this:
$query = 'update contacts set ';
if ($_POST['tel'] != '') $query .= 'TEL="'.$_POST['tel'].'", ';
if ($_POST['fax'] != '') $query .= 'FAX="'.$_POST['fax'].'", ';
if ($_POST['email'] != '') $query .= 'EMAIL="'.$_POST['email'].'", ';
$query .= "Cust_Name = '$cst' where Cust_Name = '$cst'";
The last update field: Cust_Name = '$cst' basically is to 'remove' the last comma.
Keeping in mind that $_POST values should be cleaned before use, and that all $_POST values are strings, so an empty field is '' and not null, something like this will work:
foreach ($_POST as $var=>$value) {
if(empty($value)) continue; //skip blank fields (may be problematic if you're trying to update a field to be empty)
$sets[]="$var= '$value";
}
$set=implode(', ',$sets);
$q_save="UPDATE mytable SET $set WHERE blah=$foo";
This should work (the MySQL way):
"UPDATE `custcomm_T`
SET `Telephone` = IF(TRIM('" . mysql_real_escape_string($a) . "') != '', '" . mysql_real_escape_string($a) . "', `Telephone`),
SET `Fax` = IF(TRIM('" . mysql_real_escape_string($b) . "') != '', '" . mysql_real_escape_string($b) . "', `Fax`),
SET `Mobile` = IF(TRIM('" . mysql_real_escape_string($c) . "') != '', '" . mysql_real_escape_string($c) . "', `Mobile`),
SET `EMail` = IF(TRIM('" . mysql_real_escape_string($d) . "') != '', '" . mysql_real_escape_string($d) . "', `EMail`),
SET `trlicense` = IF(TRIM('" . mysql_real_escape_string($e) . "') != '', '" . mysql_real_escape_string($e) . "', `trilicense`),
SET `trlicexp` = IF(TRIM('" . mysql_real_escape_string($f) . "') != '', '" . mysql_real_escape_string($f) . "', `trlicexp`)
WHERE Cust_Name_VC = '" . mysql_real_escape_string($g) . '";
I've tried to keep the columns and variables to what you have posted in your question, but feel free to correct as per your schema.
Hope it helps.
Loop over the optional input fields, building up which fields to set. The field names and values should be kept separate so you can use a prepared statement. You can also loop over required fields as a basic validation step.
# arrays of input => db field names. If both are the same, no index is required.
$optional = array('tel' => 'telephone', 'fax', 'email');
$required = array('custname' => 'cust_name');
# $input is used rather than $_POST directly, so the code can easily be adapted to
# work with any array.
$input =& $_POST;
/* Basic validation: check that required fields are non-empty. More than is
necessary for the example problem, but this will work more generally for an
arbitrary number of required fields. In production code, validation should be
handled by a separate method/class/module.
*/
foreach ($required as $key => $field) {
# allows for input name to be different from column name, or not
if (is_int($key)) {
$key = $field;
}
if (empty($input[$key])) {
# error: input field is required
$errors[$key] = "empty";
}
}
if ($errors) {
# present errors to user.
...
} else {
# Build the statement and argument array.
$toSet = array();
$args = array();
foreach ($optional as $key => $field) {
# allows for input name to be different from column name, or not
if (is_int($key)) {
$key = $field;
}
if (! empty($input[$key])) {
$toSet[] = "$key = ?";
$args[] = $input[$key];
}
}
if ($toSet) {
$updateContactsStmt = "UPDATE contacts SET " . join(', ', $toSet) . " WHERE cust_name = ?";
$args[] = $input['custname'];
try {
$updateContacts = $db->prepare($updateContactsStmt);
if (! $updateContacts->execute($args)) {
# update failed
...
}
} catch (PDOException $exc) {
# DB error. Don't reveal exact error message to non-admins.
...
}
} else {
# error: no fields to update. Inform user.
...
}
}
This should be handled in a data access layer designed to map between the database and program objects. If you're clever, you can write a single method that will work for arbitrary models (related forms, tables and classes).
mysql_query("
UPDATE contacts
SET
TEL = ".(is_null($a)?'TEL':"'$a'").",
FAX = ".(is_null($b)?'FAX':"'$b'").",
EMAIL = ".(is_null($c)?'EMAIL':"'$c'")."
WHERE Cust_Name = '$cst'
");

Categories