I have mysql table with following fields
id (which auto increments)
title,name,age,institution,iod
the fields like title,name,age,institution are entered in the form structure (html page) and by clicking submit button are stored in DB(mysql)
iod is the field is something like this 123/id (nothing but same id field but with '123/' prefix before)
now when the user enters title,name,age,institution these need to stored in DB including id and iod.
Now for executing the above i wrote the following the fields title,name,age,institution and id are successfully stored but iod is not stored.
Can you please show me the error i made here??
I wrote the following syntax for the code(part of the same code)
if ($_POST['title'] != '')
{
$value = $_POST['title'];
$value1 = $_POST['name'];
$value2 = $_POST['age'];
$value5 = $_POST['institution'];
$sql = "INSERT INTO parentid(title,name,age,institution) VALUES('$value','$value1','$value2','$value5')" ;
}
$sql1="SELECT * FROM parentid ORDER BY id DESC LIMIT 1";
$value6=$row['id'];
$value4= '123/' . $row['id'] ;
$sql2="UPDATE parentid SET iod='$value4' WHERE id = '$value6' ";
The problem is that you are not executing your queries, you just put the query in a string but then you donĀ“t do anything with it.
For the second query (simple sample code):
$sql1="SELECT * FROM parentid ORDER BY id DESC LIMIT 1";
$result = mysql_query($sql1);
if ($row = mysql_fetch_assoc($result))
{
$value6=$row['id'];
// etc., error handling not added
}
You didn't execute any of the queries? Also, you should escape the parameters...
if ( !empty( $_POST['title'] ) || !empty( $_POST['calc_url'] ) ) {
$value = mysql_real_escape_string( $_POST['title'] );
$value1 = mysql_real_escape_string( $_POST['name'] );
$value2 = mysql_real_escape_string( $_POST['age'] );
$value5 = mysql_real_escape_string( $_POST['institution'] );
$sql = "INSERT INTO parentid
(title,name,age,institution)
VALUES ('$value','$value1','$value2','$value5')" ;
mysql_query( $sql ) or die( mysql_error());
}
Also, you don't need a second select... Get the id by using mysql_insert_id function.
$value6 = mysql_insert_id();
$value4= '123/' . $value6 ;
And then update:
$sql2="UPDATE parentid SET iod='$value4' WHERE id = '$value6' ";
mysql_query( $sql2 );
I encorage you to use PDO or mysqli though...
Unless you've missed out chunks of code when copying/pasting into the question, there are a few problems.
Firstly, you're not actually executing the queries (I'm assuming that you are actually connecting to the database somewhere). After you assign a string to $sql, you can execute the query:
$result = mysql_query($sql);
Secondly, $row won't contain anything unless you get the data out of the dataset returned by the query:
$row = mysql_fetch_assoc($result);
Third, your if statement does not contain the UPDATE query, so that's going to execute whether or not $_POST['title'] is empty or not.
As others have mentioned, your queries are wide open to SQL injection attacks. At a minimum you will need to use mysql_real_escape_string around any inputs.
Finally, you can use mysql_insert_id to get the ID of the latest insert, instead of making another read.
Here's some attempt to rework your code (note that this is untested and could be much better):
if($_POST['title'] != '') {
//Connect to database here (or somewhere else if you already are)
$value = mysql_real_escape_string($_POST['title']);
$value1 = mysql_real_escape_string($_POST['name']);
$value2 = mysql_real_escape_string($_POST['age']);
$value5 = mysql_real_escape_string($_POST['institution']);
$sql = "INSERT INTO parentid(title,name,age,institution) VALUES('$value','$value1','$value2','$value5')";
$result = mysql_query($sql);
if($result) {
$value6 = mysql_insert_id($result);
$value4 = '123/' . $value6;
$sql2 = "UPDATE parentid SET iod='$value4' WHERE id = '$value6'";
mysql_query($sql2);
}
}
My guess is that you have a special character that needs escaping.
I'm assuming you already know you should escape all those strings before inserting them in the DB.
In PHP you have a mysql_real_escape_string function that you should use to escape each of those values.
Related
please help me out and sorry for my bad English,
I have fetch data , on basis of that data I want to update the rows,
Follows my code
I fetched data to connect API parameters
<?php
$stmt = $db->stmt_init();
/* publish store for icube*/
$stmt->prepare( "SELECT id,offer_id,name,net_provider,date,visible,apikey,networkid FROM " ."affilate_offer_findall_icube WHERE visible='1' ");
$stmt->execute();
mysqli_stmt_execute($stmt); // <--------- currently missing!!!
mysqli_stmt_store_result($stmt);
$rows = mysqli_stmt_num_rows($stmt);
$stmt->bind_result( $id, $offer_id, $name, $net_provider, $date, $visible,$apikey,$networkid);
$sql = array();
if($rows>0)
{
while($info = $stmt->fetch() ) {
$jsondataicube = file_get_contents('filename/json?NetworkId='.$networkid.'&Target=Affiliate_Offer&Method=getThumbnail&api_key='.$apikey.'&ids%5B%5D='.$offer_id.'');
$dataicube = json_decode($jsondataicube, true);
foreach($dataicube['response']['data'][0]['Thumbnail'] as $key=>$val)
{
$offer_id = $dataicube['response']['data'][0]['Thumbnail']["$key"]['offer_id'];
$display = $dataicube['response']['data'][0]['Thumbnail']["$key"]['display'];
$filename = $dataicube['response']['data'][0]['Thumbnail']["$key"]['filename'];
$url = $dataicube['response']['data'][0]['Thumbnail']["$key"]['url'];
$thumbnail = $dataicube['response']['data'][0]['Thumbnail']["$key"]['thumbnail'];
$_filename = mysqli_real_escape_string($db,$filename);
$_url = mysqli_real_escape_string($db,$url);
$_thumbnail = mysqli_real_escape_string($db,$thumbnail);
$sql[] = '("'.$offer_id.'","icube","'.$_thumbnail.'","'.$_url.'")';
}
}
As I store values which have to be inserted in 'sql'
now
$stmt->prepare( "SELECT offer_id FROM " ."affilate_offer_getthumbnail_icube ORDER BY 'offer_id' ASC");
$stmt->execute();
mysqli_stmt_execute($stmt); // <--------- currently missing!!!
mysqli_stmt_store_result($stmt);
$rows = mysqli_stmt_num_rows($stmt);
$stmt->bind_result($offer_id);
$sqlimplode = implode(',', $sql);
if($rows>0)
{
$query = "UPDATE affilate_offer_getthumbnail_icube WHERE offer_id='".$offer_id."' SET '".$sqlimplode."'";
$stmt->prepare( $query);
$execute = $stmt->execute();
}
else
{
$query= "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode;
$stmt->prepare( $query);
$execute = $stmt->execute();
}`
`
Insert query working well,but how can I update all the data like insert query ?
My Answer is refering to a "set and forget"-strategy. I dont want to look for an existing row first - probably using PHP. I just want to create the right SQL-Command and send it.
There are several ways to update data which already had been entered (or are missing). First you should alter your table to set a problem-specific UNIQUE-Key. This is setting up a little more intelligence for your table to check on already inserted data by its own. The following change would mean there can be no second row with the same value twice in this UNIQUE-set column.
If that would occur, you would get some error or special behaviour.
Instead of using PHPMyAdmin you can use this command to set a column unique:
ALTER TABLE `TestTable` ADD UNIQUE(`tablecolumn`);
After setting up your table with this additional intelligence, you alter your Insert-Command a little bit:
Instead of Insert you can drop and overwrite your Datarow with
REPLACE:
$query= "REPLACE INTO affilate_offer_getthumbnail_icube
(offer_id, net_provider,logo2020,logo100) VALUES (".$sqlimplode.")";
See: Replace Into Query Syntax
Secondly you can do this with the "On Duplicate Key"-Commando.
https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
$query= "INSERT INTO affilate_offer_getthumbnail_icube
(offer_id, net_provider,logo2020,logo100)
VALUES (".$sqlimplode.")
ON DUPLICATE KEY UPDATE net_provider = ".$newnetprovider.",
logo2020 = ".$newlogo2020.",
logo100 = ".$newlogo100.";";
Note: I think you missed some ( and ) around your $sqlimplode. I always put them around your implode. Maybe you are missing ' ' around strings as well.
Syntax of UPDATE query is
UPDATE table SET field1 = value1, field2 = value2 ...
So, you cannot pass your imploded array $sql to UPDATE query. You have to generate another sql-string for UPDATE query.
This is clearly incorrect:
$query = "UPDATE affilate_offer_getthumbnail_icube
WHERE offer_id='".$offer_id."' SET '".$sqlimplode."'";
If the intention is to INSERT offer_id='".$offer_id."' and then UPDATE ... SET offer_id = '".$sqlimplode."'";
You have to use two separate queries, one for INSERT and then another one for UPDATE
An Example:
$query = "INSERT INTO affilate_offer_getthumbnail_icube
(col_name) VALUES('".$col_Value."')";
//(execute it first);
$query2 = "UPDATE affilate_offer_getthumbnail_icube SET
col_name= '".$col_Value."'" WHERE if_any_col = 'if_any_Value';
//(execute this next);
Try this:
$sqlimplode = implode(',', $sql);
if($rows>0)
{
/*$fields_values = explode(',',trim(array_shift($sql), "()"));
$combined_arr = array_combine(['offer_id','net_provider','logo2020','logo100'],$fields_values);
$sqlimplode = implode(', ', array_map(function ($v, $k) { return $k . '=' . $v; }, $combined_arr, array_keys($combined_arr))); */
$query = "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode." ON duplicate key update net_provider = values(net_provider),logo2020 = values(logo2020),logo100 = values(logo100)";
$stmt->prepare( $query);
$execute = $stmt->execute();
}
else
{
$sqlimplode = implode(',', $sql);
$query= "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode;
$stmt->prepare( $query);
$execute = $stmt->execute();
}
I'm trying to retrieve the last id number inserted with mysql_insert_id() but always return 0, my id field is auto increment so I don't know why it returns 0 thanks. please help
include 'C:\xampp\htdocs\Student_evaluation\functions.php';
if(!loggedin())
{
header("Location: http://localhost/dev/userarea.php");
exit();
}
if(isset($_POST['submit']))
{
//get data
$name = $_POST['name'];
$f_lastname = $_POST['f_lastname'];
$second_lastname = $_POST['second_lastname'];
$student_number = $_POST['student_number'];
$semester_year = $_POST['semester_year'];
$course = $_POST['course'];
$section = $_POST['section'];
$grade = $_POST['grade'];
$student_perform = $_POST['student_perform'];
$comment_box = $_POST['comment_box'];
$sql = "INSERT INTO `students`(`name`, `first_lastname`, `second_lastname`, `numero_estudiante`, `semester`, `course`, `section`, `f_grade`, `students_perform`, `comments`)
VALUES ('$name','$f_lastname','$second_lastname','$student_number','$semester_year','$course','$section','$grade','$student_perform','$comment_box')";
$con = mysqli_connect("localhost","root","","rememberme");
$result = mysqli_query($con, $sql);
echo "ID of last inserted record is: " . mysql_insert_id();
}
You're using one library (mysqli) to perform the query, then another (mysql) to obtain the auto-increment ID. That can't work. Among other issues, you haven't even connected to the database with the second library!
Consistently use mysqli or, better yet, PDO, which will help you plug your blinding security flaw.
You should do something like this (using mysqli_insert_id):
$con = mysqli_connect("localhost","root","","rememberme");
$sql = "INSERT INTO ...";
$result = mysqli_query($con, $sql);
echo "ID of last inserted record is: " . mysqli_insert_id($con);
mysql_insert_id and mysqli_insert_id are both different and you are using mysqli so use mysqli_insert_id instead of mysql_insert_id and it's better to use mysqli instead of mysql.
I'm building a simple bug tracking tool.
You can create new projects, when you create a project you have to fill in a form, that form posts to project.class.php (which is this code)
$name = $_POST['name'];
$descr = $_POST['description'];
$leader = $_POST['leader'];
$email = $_POST['email'];
$sql="INSERT INTO projects (name, description, leader, email, registration_date)
VALUES ('$name', '$descr', '$leader', '$email', NOW())";
$result = mysql_real_escape_string($sql);
$result = mysql_query($sql);
if($result){
header('Location: ../projectpage.php?id='.mysql_insert_id());
}
else {
echo "There is something wrong. Try again later.";
}
mysql_close();
(It's not yet sql injection prove, far from complete...)
Eventually you get redirected to the unique project page, which is linked to the id that is stored in the MySQL db. I want to show the name of that project on the page, but it always shows the name of the first project in the database.
(here I select the data from the MySQL db.)
$query = 'SELECT CONCAT(name)
AS name FROM projects';
$result = mysql_real_escape_string($query);
$result = mysql_query ($query);
(here I show the name of the project on my page, but it's always the name of the first project in the MySQL db)
<?php
if ($row = mysql_fetch_array ($result))
echo '<h5>' . $row['name'] . '</h5>';
?>
How can I show the name of the right project? The one that is linked with the id?
Do I have the use WHERE .... ?
Yes, You have to use the WHERE to specify which project You want to get. I'm also not sure why are You using CONCAT function when You want to get only one project.
Other important thing is that You have to use mysql_real_escape_string() function on parameters before You put them in the query string. And use apropriate functions for specific type of data You receive.
So Your statement for getting the project should look like this:
SELECT name FROM projects WHERE id = ' . intval($_GET['id'])
Also when before You use the mysql_fetch_assoc() function, check if there are any records in the result with
if(mysql_num_rows($result) > 0)
{
$project = mysql_fetch_assoc($result);
/* $project['name'] */
}
try this
// first get the id, if from the url use $_GET['id']
$id = "2";
$query = "SELECT `name` FROM `projects` WHERE `id`='".intval($id). "'";
$result = mysql_query(mysql_real_escape_string($query));
use mysql_fetch_row, here you'll not have to loop through each record, just returns single row
// if you want to fetch single record from db
// then use mysql_fetch_row()
$row = mysql_fetch_row($result);
if($row) {
echo '<h5>'.$row[0].'</h5>';
}
$row[0] indicates the first field mentioned in your select query, here its name
The might be of assistance:
Your are currently assing a query string parameter projectpage.php?id=
When you access the page the sql must pick up and filter on the query string parameter like this:
$query = 'SELECT CONCAT(name) AS name FROM projects WHERE projectid ='. $_GET["id"];
$result = mysql_real_escape_string($query);
$result = mysql_query ($query);
Also maybe move mysql_insert_id() to right after assigning the result just to be safe.
$result = mysql_query($sql);
$insertId = mysql_insert_id();
Then when you assign it to the querystring just use the parameter and also the
header('Location: ../projectpage.php?id='.$insertId);
I have create a profile page in php. The page includes the address and telephone fields and prompts the users to insert their data. Data are then saved in my table named profile.
Everything works fine, but the problem is that the table updated only if it includes already data. How can I modify it (probably mysql query that I have in my function), so that data will be entered into the table even if it is empty. Is there a something like UPDATE OR INSERT INTO syntax that I can use?
Thanks
<?php
if ( isset($_GET['success']) === true && empty($_GET['success'])===true ){
echo'profile updated sucessfuly';
}else{
if( empty($_POST) === false && empty($errors) === true ){
$update_data_profile = array(
'address' => $_POST['address'],
'telephone' => $_POST['telephone'],
);
update_user_profile($session_user_id, $update_data_profile);
header('Location: profile_update.php?success');
exit();
}else if ( empty($errors) === false ){
echo output_errors($errors);
}
?>
and then by using the following function
function update_user_profile($user_id, $update_data_profile){
$update = array();
array_walk($update_data_profile, 'array_sanitize');
foreach($update_data_profile as $field => $data )
{
$update[]='`' . $field . '` = \'' . $data . '\'';
}
mysql_query(" UPDATE `profile` SET " . implode(', ', $update) . " WHERE `user_id` = $user_id ") or die(mysql_error());
}
I'm new to the posted answer by psu, and will definatly check into that, but from a quick readthrough, you need to be very careful when using those special syntaxes.
1 reason that comes to mind: you have no knowledge of what might be happening to the table that you're inserting to or updating info from. If multiple uniques are defined, then you might be in serious trouble, and this is a common thing when scaling applications.
2 the replace into syntax is a functionality i rarely wish to happen in my applications. Since i do not want to loose data from colomns in a row that was allready in the table.
i'm not saying his answer is wrong, just stating precaution is needed when using it because of above stated reasons and possible more.
as stated in the first article, i might be a newbie for doing this but at this very moment i prefer:
$result = mysql_query("select user_id from profile where user_id = $user_id limit 1");
if(mysql_num_rows($result) === 1){
//do update like you did
}
else{
/**
* this next line is added after my comment,
* you can now also leave the if(count()) part out, since the array will now alwayss
* hold data and the query won't get invalid because of an empty array
**/
$update_data_profile['user_id'] = $user_id;
if(count($update_data_profile)){
$columns = array();
$values = array();
foreach($update_data_profile as $field => $data){
$columns[] = $field;
$values[] = $data;
}
$sql = "insert into profile (" . implode(",", $columns) .") values ('" . implode("','", $values) . "')" ;
var_dump($sql); //remove this line, this was only to show what the code was doing
/**update**/
mysql_query($sql) or echo mysql_error();
}
}
You cannot update the table if there isn't any data in it corresponding the user_id, meaning that you must have a row containing the user_id and null or something else for the other fields.
a) You can try to check if the table contains data and if not insert it else use update (not ideal)
$result = mysql_query("UPDATE ...");
if (mysql_affected_rows() == 0)
$result = mysql_query("INSERT ...");
b) Checkout this links
http://www.kavoir.com/2009/05/mysql-insert-if-doesnt-exist-otherwise-update-the-existing-row.html
http://dev.mysql.com/doc/refman/5.0/en/replace.html
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
#Stefanos
you can use use "REPLACE INTO " command in place of "INSERT INTO" in the SQL query.
for example
Suppose you have insert query
INSERT INTO EMPLOYEE (NAME,ADD) values ('ABC','XYZZ');
Now you can use following query as combination of insert and update
REPLACE INTO EMPLOYEE (NAME,ADD) values ('ABC','XYZZ');
Hope this will help!
My update form script works only, if I use numbers but, if I try use any words it won't work. I need help, thanks!
<?php
if(isset($_POST['teams'])){
$home_team = $_POST['home_team'];
$visitor_team = $_POST['visitor_team'];
$sql = mysql_query("UPDATE table1
SET home_team = $home_team, visitor_team = $visitor_team
WHERE active = 1") ;
$retval = mysql_query( $sql, $conn );
if(! $retval ){
die("<p>Error! Could not update team names. Click return button.</p>");
}
echo "<p>Team names set successfully!</p>";
mysql_close($conn);
}
?>
try with use of '' into your query,
$sql = mysql_query("UPDATE table1 SET
home_team = '".mysql_real_escape_string($home_team)."',
visitor_team = '".mysql_real_escape_string($visitor_team)."'
WHERE active = '1'") ;
also add mysql_real_escape_string() to prevent from SQL Enjection..
Every string passed to a SQL statement must be enclosed within a ''; if they are not, it will result in an error.
That being said, throwing content straight from a form into the database is very, very, very, very (I need another very) bad. Your database can simply be wiped by anyone; it's called SQL injection
To protect your database, you can start with this good article on PDO