I want to execute a mysql query from php.
$sql = insert into q_links values ( 'garment.png', 'imgs\ques\p1\garment.png' );
I couldn't store the url as it is, rather it is being stored like this: imgsquesp1garment.png. But I want to store the url like: imgs\ques\p1\garment.png. So I tried this:
$sql = mysql_real_escape_string($sql);
But this way my $sql looks like:
insert into q_links values ( \'garment.png\', \'imgs\\ques\\p1\\garment.png\' );
which do not work in the mysql database.
I have to insert this url in the database for later use. The url is imgs\ques\p1\garment.png. How can I achieve this?
Update:
And I tried with the first comment which worked for me.
So the solution is:
$sql = "insert into q_links values ( 'garment.png', '".mysql_real_escape_string( 'imgs\ques\p1\garment.png' )."' );";
$url = "imgs\ques\p1\garment.png";
$url = mysql_real_escape_string($url);
$sql = "INSERT INTO q_links VALUES ('garment.png', '$url')";
As a side note, the mysql_* functions are deprecated, and you should move to Prepared statements with mysqli_* or PDO.
Example in PDO:
$pdo = new PDO("mysql:host=localhost;port=3306;dbname=mydb", "user", "password");
$stmt = $pdo->prepare("INSERT INTO q_links VALUES (?, ?)");
$stmt->execute(array("garment.png", "imgs\ques\p1\garment.png"));
$stmt->closeCursor();
Add the escape only for img field:
$sql = "insert into q_links values ( 'garment.png', '".mysql_real_escape_string( 'imgs\ques\p1\garment.png' )."' );"
don't escape the single quote, only the \
$var = "insert into q_links values ( 'garment.png', 'imgs\\ques\\p1\\garment.png');"
Why don't you store it with forward slashes as such?
$sql = insert into q_links values ( 'garment.png', 'imgs/ques/p1/garment.png' );
I can be like this:
$img=addslashes("imgs\ques\p1\garment.png");
$sql=insert into q_links values('garment.png',$img);
and while retriving you can use stripslashe();
You can use this code to enter image url in database
$url =mysql_real_escape_string('imgs\ques\p1\garment.png');
$sql = "insert into q_links values ( 'garment.png', '".$url."' );
if you execute the query:
insert into q_links values ( 'garment.png', 'imgs\ques\p1\garment.png' );
it will insert successfully in database
Use PDO. mysql_ is deprecated anyway.
$params = array('value_one','value_two')
$dbh = new PDO('credentials go here');
$sql = 'insert into q_links values ( ?, ? );';
$stmt = $dbh->prepare($sql);
$stmt->execute($params);
Using PDO you would prepare your statement and then call execute it with the exacte variable you want. It would escape it all for you.
Related
I am trying to insert data into a database after the user clicks on a link from file one.php. So file two.php contains the following code:
$retrieve = "SELECT * FROM catalog WHERE id = '$_GET[id]'";
$results = mysqli_query($cnx, $retrieve);
$row = mysqli_fetch_assoc($results);
$count = mysqli_num_rows($results);
So the query above will get the information from the database using $_GET[id] as a reference.
After this is performed, I want to insert the information retrieved in a different table using this code:
$id = $row['id'];
$title = $row['title'];
$price = $row['price'];
$session = session_id();
if($count > 0) {
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
The first query $retrieve is working but the second $insert is not. Do you have an idea why this is happening? PS: I know I will need to sanitize and use PDO and prepared statements, but I want to test this first and it's not working and I have no idea why. Thanks for your help
You're not executing the query:
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
it needs to use mysqli_query() with the db connection just as you did for the SELECT and make sure you started the session using session_start(); seeing you're using sessions.
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
$results_insert = mysqli_query($cnx, $insert);
basically.
Plus...
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
If that still doesn't work, then MySQL may be complaining about something, so you will need to escape your data and check for errors.
http://php.net/manual/en/mysqli.error.php
Sidenote:
Use mysqli_affected_rows() to check if the INSERT was truly successful.
http://php.net/manual/en/mysqli.affected-rows.php
Here's an example of your query in PDO if you'req planning to use PDO in future.
$sql = $pdo->prepare("INSERT INTO table2 (id, title, price, session_id) VALUES(?, ?, ?, ?");
$sql->bindParam(1, $id);
$sql->bindParam(2, $title);
$sql->bindParam(3, $price);
$sql->bindParam(4, $session_id);
$sql->execute();
That's how we are more safe.
Ok so I execute the following code for inserting data into database:
$db_conn->beginTransaction();
$query = $db_conn->prepare('INSERT INTO mytable(name, user) VALUES(:name, :user)');
foreach($UploadData AS $DataValue)
{
$query->execute(array(':name' => $DataValue['Name'],':user' =>$_SESSION['user']));
}
$db_conn->commit();
Now in this code block execute() runs 100s time if I have that much data. Like before I use to do with basic mysqli concatenation and executes the query only once.
Will that can be done here with PDO also?
$SQL = 'INSERT INTO mytable (name, user) VALUES';
foreach( $UploadData AS $DataValue)
$SQL .= sprintf(" ( '%s', '%s' ),", $DataValue['Name'], $DataValue['user'] );
$SQL = substr($SQL, -1);
$query = $db_conn->prepare($SQL);
$query->execute();
Result
INSERT INTO mytable (name, user) VALUES ('VAL', 'VAL'), ('VAL', 'VAL') ....
I have variable set to NULL that im trying to insert into a database but for some reason they keep getting submitted as '0'. Im positive that column im trying to inset into allows NULL and that the default is set to to NULL. Heres my code:
$insert = NULL;
$query = mysql_query("INSERT INTO `table1` (column1) VALUES ('$insert')") or die(mysql_error());
Warning:
Please, don't use mysql_* functions for new code. They are no longer maintained and the community has begun the deprecation process. Instead you should learn about prepared statements and use either PDO or MySQLi.
IF you want it to be NULL (and you really really still want to use mysqli_*) in the database you can do the following:
$insert = NULL;
$query = mysql_query("INSERT INTO `table1` (column1) VALUES ("
.(($insert===NULL)?
"NULL":
"'".mysql_real_escape_string($insert)."'").
")") or die(mysql_error());
But this could lead to nefarious SQL injection and is not recommended.
See Bobby Tables
So: all in all you should be using prepared statements.
You can use MySQLi like so:
$dbHandle = new mysqli(...);
$query = "INSERT INTO `table1` (column1) VALUES (?)";
$statement = $dbHandle->prepare($query);
if($statement){
$statement->bind_param('s', $insert);
if(!$statement->execute()){
echo "Statement insert error: {$statement->error}";
}
$statement->close();
}
else {
echo "Insert error: {$dbHandle->error}";
}
Try this for static query:
$query = mysql_query("INSERT INTO `table1` (column1) VALUES (NULL)") or die(mysql_error());
Using Variable :
$insert= NULL;
$insert = ($insert===NULL)? 'NULL' : "'$insert'";
mysql_query("INSERT INTO `table1` (column1) VALUES ($insert)") or die(mysql_error());
Try without the quotes;
$query = mysql_query("INSERT INTO `table1` (`column1`) VALUES (".$insert.")") or die(mysql_error());
The query should be;
INSERT INTO table1 (column1) VALUES (NULL);
So, I'm not exactly sure what the problem is, but, when I try to INSERT into a table, it doesn't work.
All the variables are working. I've echoed and tested them, they are working.
$username = $_SESSION['username'];
$update = $_GET['update'];
mysql_query("INSERT INTO updates (username, update) VALUES ('$username', '$update')");
So it must be a problem with my mySQL query. This mySQL query is one of two in the .php folder. If that makes any difference.
Error in SQL
There is an error in your SQL. You cannot use MySQL keywords in column names without quoting them.
In this case update needs to be enclosed in backticks:
$query = "INSERT INTO updates (`username`, `update`)
VALUES ('$username', '$update')";
SQL injection
Your code is susceptible to SQL injection attacks. You should escape quoted strings that are placed into an SQL statement with mysql_real_escape_string() or bind your data using PHP PDO prepared statements.
$username = mysql_real_escape_string($_SESSION['username']);
$update = mysql_real_escape_string($_GET['update']);
Putting it together
$username = mysql_real_escape_string($_SESSION['username']);
$update = mysql_real_escape_string($_GET['update']);
$query = "INSERT INTO updates (`username`, `update`)
VALUES ('$username', '$update')";
I have written little SQLFiddle for you so you can see this in action: http://sqlfiddle.com/#!2/c25b1/1
You need to escape the data you are about to insert. You also want to separate the string from the variables.
Try something like this:
$username = mysql_real_escape_string($_SESSION['username']);
$update = mysql_real_escape_string($_GET['update']);
mysql_query("INSERT INTO `updates` (username, update) VALUES ('" . $username . "', '" . $update . "')") or die(mysql_error());
That's untested but should work.
mysql_error() is the best way but you can also echo your query and run it directly against the database to see what is the problem.
$username = $_SESSION['username'];
$update = $_GET['update'];
$query = "INSERT INTO updates (username, update) VALUES ('$username', '$update')";
mysql_query($query);
echo "My Query : $query";
try this:
$username = $_SESSION['username'];
$update = $_GET['update'];
mysql_query("INSERT INTO updates (username, update) VALUES ('+$username', '+$update')");
also is better is create a variable to put the query string and then you make the query
mysql_insert_id does not return the last inserted id when i place it inside a function.
im kinda confused why it does not.
here is my code:
function addAlbum($artist,$album,$year,$genre) {
$connection = mysql_connect(HOST,USER,PASS);
$sql = 'INSERT INTO `'.TABLE_ARTIST.'` (artistName) VALUES ("'.$artist.'")';
$resultArtist = mysql_query($sql);
$sql = 'INSERT INTO `'.TABLE_ALBUMS.'` (albumName) VALUES ("'.$album.'")';
$resultAlbums = mysql_query($sql);
$sql = 'INSERT INTO `'.TABLE_GENRE.'` (musicGenre) VALUES ("'.$genre.'")';
$resultGenre = mysql_query($sql);
$sql = 'INSERT INTO `'.TABLE_YEAR.'` (albumYear) VALUES ("'.$year.'")';
$resultYear = mysql_query($sql);
$lastId = mysql_insert_id();
$sql = 'INSERT INTO `'.TABLE_LINK.'` (albumsId,artistId,genreId,yearId) VALUES ("'.$lastId.'","'.$lastId.'","'.$lastId.'","'.$lastId.'")';
$resultLink = mysql_query($sql);
if(!$resultArtist && $resultAlbums && $resultGenre && $resultYear && $resultLink){
echo mysql_error();
}
}
thanks in advance
adam
You are calling mysql_insert_id() once after four separate INSERTs, and using that ID four times for albumsId, artistId, genreId and yearId. That doesn't seem right.
You should also check that your tables are using AUTO_INCREMENT fields. If not, mysql_insert_id() will not return the insert ID. See the docs:
http://www.php.net/manual/en/function.mysql-insert-id.php
I highly recommend that you use prepared statements with mysqli::prepare, perhaps via PDO. It's ultimately simpler and safer. Here's an untested example:
$dsn = 'mysql:dbname=test;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
$dbh = new PDO($dsn, $user, $password);
$stmt_artist = $dbh->prepare(
'INSERT INTO `table_artist` (artistName) VALUES (?)'
);
$stmt_albums = $dbh->prepare(
'INSERT INTO `table_albums` (albumName) VALUES (?)'
);
$stmt_genre = $dbh->prepare(
'INSERT INTO `table_genre` (musicGenre) VALUES (?)'
);
$stmt_year = $dbh->prepare(
'INSERT INTO `table_year` (albumYear) VALUES (?)'
);
$stmt_link = $dbh->prepare(
'INSERT INTO `table_link` (albumsId, artistId, genreId, yearId) '.
'VALUES (?, ?, ?, ?)'
);
$stmt_albums->execute(array( $artist ));
$artist_id = $dbh->lastInsertId();
$stmt_albums->execute(array( $album ));
$album_id = $dbh->lastInsertId();
$stmt_genre->execute(array( $genre ));
$genre_id = $dbh->lastInsertId();
$stmt_year->execute(array( $year ));
$year_id = $dbh->lastInsertId();
$stmt_link->execute(array( $artist_id, $album_id, $genre_id, $year_id ));
You need to call it separately for each insert, and store the result of each call separately. Like this:
$sql = 'INSERT INTO `'.TABLE_ARTIST.'` (artistName) VALUES ("'.$artist.'")';
$resultArtist = mysql_query($sql);
$lastArtistId = mysql_insert_id();
$sql = 'INSERT INTO `'.TABLE_ALBUMS.'` (albumName) VALUES ("'.$album.'")';
$resultAlbums = mysql_query($sql);
$lastAlbumId = mysql_insert_id();
$sql = 'INSERT INTO `'.TABLE_GENRE.'` (musicGenre) VALUES ("'.$genre.'")';
$resultGenre = mysql_query($sql);
$lastGenreId = mysql_insert_id();
$sql = 'INSERT INTO `'.TABLE_YEAR.'` (albumYear) VALUES ("'.$year.'")';
$resultYear = mysql_query($sql);
$lastYearId = mysql_insert_id();
$sql = 'INSERT INTO `'.TABLE_LINK.'` (albumsId,artistId,genreId,yearId) VALUES ("'.$lastAlbumId.'","'.$lastArtistId.'","'.$lastGenreId.'","'.$lastYearId.'")';
Also, it only works if each of tables you're inserting into has AUTO_INCREMENT enabled.
Did you ever try to debug your code?
With echo() (for showing your SQL queries) or var_dump() (for checking the results of e. g. mysql_insert_id(), mysql_query()).
Also check mysql_error().
Furthermore be sure to set the resource identifier in your mysql_*() functions. It's possible to have more than just one open MySQL resource - so be sure to identify the resource.
For example:
$result = mysql_query($SQL, $connection);
$lastInsertID = mysql_insert_id($connection);
And - it's very important to know that mysql_insert_id() just works with tables which have an AUTO_INCREMENT-field.
And what's also interesting with your code: you call mysql_insert_id solely after the last of 5 queries. Is this really wanted? So you only receive the ID of your last INSERT query.