Will this update my sql information? - php

Stupid title I know. I have this:
$x = array_keys($_POST);
foreach($x as $y) {
$query = "UPDATE * FROM events (PromotionalTimeLine = "$_POST[$y]" WHERE EventID='$y'";
$result = mysql_query($query);
print_r($result);
}
I need to update only the PromotionalTimeLine cell for specific rows with $y as their EventID. Will this do that?

No, You have mysql syntax error with update query.
$query = "UPDATE events
SET PromotionalTimeLine = '".mysql_real_escape_string($_POST[$y])."'
WHERE EventID='".$y."'";

You string concatenation has some problems. It should be
$query = "UPDATE events SET PromotionalTimeLine = '" .$_POST[$y]. "' WHERE EventID='".$y."'";
And also you have not sanitized your input, Which I'd advise you to do so the cose is not vulnerable to SQL injection or similar attacks. Here is an detailed post on sanitizing input - What's the best method for sanitizing user input with PHP?

Incidentally, none of the other answers worked for me. This worked though:
mysql_query("UPDATE events
SET PromotionalTimeLine = '$_POST[$y]'
WHERE EventID='$y' ");

Related

How to add string value to cell in SQL using php?

I am trying to update varchar cell in SQL users table. Now the value of groups_id is 3. $last_id = 4. I want to change it to 3, 4. Could you please tell me what I am doing wrong?
With this code the value remains the same
$sql = "UPDATE registration.users SET groups_id = groups_id+', $last_id' WHERE username = '$user_name'";
$update_groups_id = $db->query($sql);
$val = $groups_id . ", ".$last_id;
$sql = "UPDATE registration.users SET `groups_id` = '$val' WHERE username = '$user_name'";
$update_groups_id = $db->query($sql);
your SQL query is wrong, you are not concatenating variables properly, try doing this way, I think it should help you
There is a syntax fault in your $sql object as you use +', $last_id'. If you want to append in PHP you can use . in string context
Also I'm pretty sure you can leave the '' from the variables so '$last_id' will become $last_id
But more important is that you do not check for any security issues. I hope $user_name and $last_id are not just taken from the input as SQL injections are possible.
I recommend you to look at mysqli_prepare and mysqli_bind

How to solve Illegal string offset ['id'] in php?

I'm sorry if this is a duplicate question but I don't know how to solve my problem. Every time I try to correct my error I fail. My code is:
if (isset($_GET["comment"])) {$id = $_GET["comment"];}
$query = "SELECT * FROM posts WHERE id = {$id['$id']};";
$get_comment = mysqli_query($con, $query);
Can anybody correct the code to not show an error anymore and tell me what did I wrong?
Try this:
$id = isset($_GET['comment']) ? $_GET['comment'] : 0;
$query = "SELECT * FROM `posts` WHERE `id` = " . intval($id);
The use of intval will protect you from SQL injection in this particular case. Ideally, you should learn PDO as it is extremely powerful and makes prepared statements much easier to handle to prevent all injections.
An example using PDO might look like:
$id = isset($_GET['comment']) ? $_GET['comment'] : 0;
$query = $pdo->prepare("SELECT * FROM `posts` WHERE `id` = :id");
$query->execute(array("id"=>$id));
$result = $query->fetch(PDO::FETCH_ASSOC); // for a single row
// $results = $query->fetchAll(PDO::FETCH_ASSOC); // for multiple rows
var_dump($result);
First of all you should prevent injestion.
if (isset($_GET["comment"])){
$id = (int)$_GET["comment"];
}
Notice, $id contanis int.
$query = "SELECT * FROM posts WHERE id = {$id}";
Assuming your $id is an integer and you only want to make the query if it is set, here's how you could do it using prepared statements, which protect you from MYSQL injection attacks:
if (isset($_GET["comment"])) {
$id = $_GET["comment"];
$stmt = mysqli_prepare($con, "SELECT * FROM posts WHERE id = ?");
mysqli_stmt_bind_param($stmt, 'i', $id);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $get_comment);
while (mysqli_stmt_fetch($stmt)) {
// use $get_comment
}
mysqli_stmt_close($stmt);
}
Most of these functions return a boolean indicating whether they were successful or not, so you might want to check their return values.
This approach looks a lot more heavy duty and is arguably overkill for a simple case of a statement containing a single integer but it's a good practice to get into.
You might want to look at the object-oriented style of mysqli which you might find a little cleaner-looking, or alternatively consider using PDO.

Php update function

I wrote this code
if(isset($_POST['update'])) {
$webname = $_POST['webname'];
$webmeta = $_POST['webmeta'];
$webdesc = $_POST['webdesc'];
$sql=("UPDATE settings (name, meta, description) VALUES ('$webname', '$webmeta', '$webdesc')");
}
but the problem is that it doesn't update my database, and I cannot find anything wrong in the code ...
I have name "update" on submit button, and all my fields are the same as in code
That's insert! Not update!
$sql=("UPDATE `settings` SET `name` = '$webname',
`meta` = '$webmeta',
`description` = '$webdesc')
WHERE [some condition]");
And replace the [some condition] with a valid condition.
Your code is heavily vulnerable to SQL Injection.
Consider escaping the input by replacing these:
$webname = $_POST['webname'];
$webmeta = $_POST['webmeta'];
$webdesc = $_POST['webdesc'];
With:
$webname = mysql_real_escape_string($_POST['webname']);
$webmeta = mysql_real_escape_string($_POST['webmeta']);
$webdesc = mysql_real_escape_string($_POST['webdesc']);
Or something equivalent like PDO or MySQLi.
mysql_select_db("my_db", $con);
mysql_query("UPDATE Persons SET Age=36
WHERE FirstName='Peter' AND LastName='Griffin'");
u need to first formulate query ans then run/ execute that
$query = "UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value";
// Perform Query
$result = mysql_query($query);
You need to run
$connection = mysql_connect($server, $serv_Username, $serv_Password);
mysql_select_db($dbase_name, $connection);
mysql_query($update_query, $connection));
I don't know if this is your problem (don't know how much you know about PHP so just saying).
Also your syntax is wrong. Should be:
UPDATE tablename SET column_name='some_value' WHERE column_name ='some_value'
note that this is diffrent from mentioned above without the thingys covering the column_name parameters.
better is to use PDO as mentioned above, mysql_ can be used "safely" on < PHP 5.5.
Try The code shown below
Just replace the field names and values with your information on your database
$editid=$_POST['editid'];
$username=callback($_POST['username']);
$password=callback($_POST['password']);
$name=callback($_POST['name']);
$age=callback($_POST['age']);
$phone=callback($_POST['phone']);
$emailaddress=callback($_POST['emailaddress']);
$gender=callback($_POST['gender']);
$description=callback($_POST['description']);
$update=update("users","username='".$username."',password='".$password."',name='".$name."',age='".$age."',phone='".$phone."',emailaddress='".$emailaddress."',gender='".$gender."',description='".$description."' ","ID='".$editid."' " );

Insert query problem with php mysql

This is simple one i am using the following insert query
mysql_query(insert into table1 set saltval = 'Y'Z' where uid ='1');
but i does not work becaues the value for the field saltval is Y'Z . my question is how to considered this value is as a string .
You need to escape any single quotes with a backslash.
mysql_query("insert into table1 set saltval = 'Y\'Z' where uid ='1'");
However your SQL is invalid as well... Did you mean to do an update? Insert statements don't have a where.
As mentioned in other answers, if the input is from a user then you should use mysql_real_escape_string()
http://www.php.net/manual/en/function.mysql-real-escape-string.php
$string = mysql_real_escape_string("Y'Z");
mysql_query("insert into table1 set saltval = '{$string}' where uid ='1'");
Always use mysql_real_escape_string() function for this if values come from user input
$query="insert into table1 set saltval = '".mysql_real_escape_string($InputVal)."' where uid ='1'";
See http://php.net/manual/en/function.mysql-real-escape-string.php
You have to add a backslash to certain characters to make your string fit into SQL syntax rules.
Assuming you're creating your query dynamically, PHP has special escaping function for this and you should use it for the every quoted string in the query, no exceptions.
So, write your code like this:
$salt = "Y'Z";
$id = 1;
$salt = mysql_real_escape_string($salt);
$id = mysql_real_escape_string($id);
$sql = "update table1 set saltval = '$salt' where uid ='$id'";
mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
to make it safe and fault-tolerant

Set variable from SELECT PHP

I simply want to define the variable "$read" as whatever its value is in the database. How can I do this?
$read = "SELECT `read` FROM `users` WHERE `id` = '$id'";
$read = mysql_result(mysql_query("SELECT read FROM users WHERE id = $id"),0);
Beware of the answers given using mysql_query, as they're vulnerable to SQL injection.
If $id is supplied by a user, you should never directly put it into the SQL query, but rather use a prepared statement.
One way of doing this, is by using PDO, in a manner similar to this:
$dbh = new PDO($connStr, $user, $pass);
$sql = "SELECT `read` FROM `users` WHERE `id` = :id";
$statement = $dbh->prepare($sql);
$statement->execute( array('id' => $id) );
$read = $statement->fetchColumn();
For more information on how to use PDO, see the following:
Are there good tutorials on how to use PDO?
One way to accomplish this is as follows:
// Run the query
$db_result = mysql_query("SELECT read FROM users WHERE id = $id");
// Get the first row (in this case you'll only get one row)
$row = mysql_fetch_array($db_result, MYSQL_NUM);
// Get the first column (you should only have one column anyway) and put it into your variable
$read = $row[0];
As pointed out below, I should add that if you don't trust $id to be properly escaped, you could be vulnerable to SQL injection. To overcome this, you should either make sure you properly escape and validate $id or use some kind of binding or prepared statement to do it for you, like in this question or in the example below.
I know it's almost impossible to teach someone something, especially if they don't want to learn. But in hope it will be useful for someone else
All modern programming languages supports such a thing called "user defined functions".
A very handy feature.
A programmer, who wants to have their code real neat, can make a function out of some repetitive code and make calling this code REAL small, just almost as it was phrased in the OP:
$read = dbgetvar("SELECT `read` FROM `users` WHERE `id` = %d",$id);
another benefit from such an approach - your code could contain all necessary things, like parameter sanitization and error handling. And still calling this code would be shorter than all codes above, made ugly and unmantainable in pursue for shortness.
An example of such a function
function dbgetvar(){
$args = func_get_args();
$query = array_shift($args);
$query = str_replace("%s","'%s'",$query);
foreach ($args as $key => $val) {
$args[$key] = mysql_real_escape_string($val);
}
$query = vsprintf($query, $args);
$res = mysql_query($query);
if (!$res) {
trigger_error("dbget: ".mysql_error()." in ".$query);
return FALSE;
}
$row = mysql_fetch_row($res)
if (!$row) return NULL;
return $row[0];
}
I would do the following:
// leave the single quotes around $id because it most probably is an INT
// LIMIT 1 will make the query a bit faster
$result = mysql_query("SELECT `read` FROM `users` WHERE `id` = $id LIMIT 1");
$row = mysql_fetch_row($result);
$read = $row[0];
Hope it works for you.
Assuming there is only 1 result:
$read = mysql_fetch_array(mysql_query("SELECT read FROM users WHERE id = $id"));
$read = $read[0];

Categories