I recently received -3 ratings for my recent question though the solution wasn't provided. My apologies if I posted something which I shouldn't have.
Alright so it is related to that ques only I have this code:
$data = mysql_connect("localhost", "user", "pass");
mysql_select_db("dbname");
$data = mysql_query("SELECT `location` FROM `upload` WHERE `name` = '".$result['name']."'")
or die(mysql_error());
$info = mysql_fetch_array( $data );
$display_url = $info['createlink'];
So when I echo $display_url it returns nil value and in db I checked the createlink field and the value stored there is a link.
And when I use
$display_url = $info['location'];
It returns perfect value.
~~The field at createlink contains 'http://www.exdomain.com/create/create.php?t=BATMAN_SLAPPING_ROBBIN.jpg'
~~The field at location contains 'http://www.exdomain.com/create/img/BATMAN_SLAPPING_ROBBIN.jpg'
You're not requesting the createlink field from the table, only location. Change your query to this:
$data = mysql_query("SELECT `location`,`createlink` FROM `upload` WHERE `name` = '".$result['name']."'")
You should also move away from the deprecated mysql_* functions and switch to PDO/mysqli so that your code will work in future versions of php. This will also allow you to parametrize your queries to prevent SQL injection.
Related
I'm developing an app for android that uses a DB on a server.
I wrote some script php to create new rows in some tables and get all elements from a table (using JSON to exchange data between android and mysql).
Now I have a problem:
i need to select an id from a table and then use this to insert a row in anothere table that has this foreign key.
Well, when I try to select my id, i don't know why, but look like it doesn't work.
Here a simple example how I select this id:
//connect to DB...
$result = mysql_query (*SELECT id FROM 'table' WHERE name = $name );
$row = mysql_fetch_assoc($result);
$id = $row['id'];
When i use this to select an id, and put it in another query (always on the same connectio) nothing is stored.
if I force the value manually, and so in the same second query I put a number of a preesisting id, the insert works, so the problem is in this piece of code.
Hope someone could help me.
Thank you!
The code that you have put on the question, contains syntax errors.
- Remove * from the start of query
- put the query inside " "
- remove single quote ('table') from table name
Here is the modified code:
//connect to DB...
$result = mysql_query ("SELECT id FROM table WHERE name = $name" );
$row = mysql_fetch_assoc($result);
$id = $row['id'];
Also you should escape the parameter $name in query. And you should use mysqli or PDO instead of mysql extension.
try this:
$result = mysql_query (*SELECT id FROM 'table' WHERE name = $name );
$row = mysql_fetch_assoc($result);
while($row > 0){
$id = $row['id'];
}
I'm toying around with mysql and PHP and hit a VERY strange problem:
After establishing a successful database connection I set two variables for the query:
$searchcolor = $_SESSION["color"];
$searchprice = $_POST["price"];
$query = "SELECT `toys`.`id` FROM `database`.`toys` WHERE `toys`.`color` = $searchcolor AND `toys`.`price` = $searchprice;";
$result = mysqli_query($link, $query);
echo $query;
This querys won't work. When echoing it, it reads the correct string, like:
SELECT `toys`.`id` FROM `database`.`toys` WHERE `toys`.`color` = brown AND `toys`.`price` = 1500;
This code, however, works just fine:
$searchcolor = $_SESSION["color"];
$searchprice = $_POST["price"];
$query = "SELECT `toys`.`id` FROM `database`.`toys` WHERE `toys`.`color` = $searchcolor AND `toys`.`price` = 1500;";
$result = mysqli_query($link, $query);
echo $query;
First I though the $searchprice wasn't getting it's content by the $_POST array correctly. But the echoed search query in the first example seems to be fine.
It also works when setting $searchprice = 1500; instead of getting the $_POST-value.
I tried casting it to integer and stuff, but that didn't worked.
Cheers and thanks for every hint on this!
(The code is shortened!)
Table structure of toys:
id int(10)
name varchar(10)
color varchar(10)
price int(20)
Edit:
Woah, just made an interesting discovery:
echo "-".$searchprice."-";
Gives -5-
if ($searchprice == 5){echo "1";}
if ($searchprice == "5"){echo "2";}
Gives.. nothing?!
var_dump($searchprice);
Gives string(14) "5"
Edit:
echo bin2hex($searchprice);
Gives 3c6e6f62723e353c2f6e6f62723e (?!)
Solution: I used a unicode character in the submitting form. That broke everything. Lesson: Avoid unicode.
First of all you should read this: How can I prevent SQL injection in PHP?
Try this:
$q = mysqli_prepare($link, 'SELECT toys.id FROM toys WHERE toys.color = ? AND toys.price = ?');
mysqli_stmt_bind_param($q, 'si', $searchcolor, $searchprice); //d for double
$searchcolor = $_SESSION['color'];
$searchprice = $_POST['price'];
mysqli_stmt_execute($q);
Before that you should connect properly with DB. I see that you used database in FROM.
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
I've create database, which basically accept name and Id and answer string of
length 47,and my php code will grade the incoming results against the answer key I provided and number containing the count of correct answers will stored in database. this is information of my database.
database name is marking
and table called 'answer', which has 5 fields as follow
1) answer_id :int , not null, auto increament.
2) name: text
3)id : text
4)answers : text
5)correct : int
my question and problem is the function is working
// setup query
$q = mysql_query("INSERT INTO `answer` VALUES
(NULL,'$name', '$id','$answers','$correct')");
// run query
$result = mysql_query($q);
or in another way , nothing storing in my database ???
Thanks in advance.
this is the whole program.
<?php
error_reporting(E_ALL ^ E_STRICT);
// to turn error reporting off
error_reporting(0);
$name =$_POST['name'];
$id = $_POST['id'];
$answers = $_POST['answers'];
// check the length of string
if(strlen($answers) !=10)
{
print'your answer string must be 10';
return;
}
mysql_connect("localhost","root","");
mysql_select_db("marking");
$name = addslashes($name);
$id = addslashes($id);
$answers = addslashes($answers);
$answer_key = "abcfdbbjca";
$correct = 0;
for($i=0;$i<strlen($answer_key);$i++)
{
if($answer_key[$i] == $answers[$i])
$correct++;
}
// Setup query
$q = mysql_query("INSERT INTO `answer` VALUES ('$name', '$id','$answers','$correct')");
$result = mysql_query($q);
print 'Thnak you. You got' + $correct + 'of 10 answers correct';
?>
Try this:
// setup query
$q = "INSERT INTO `answer` (`name`, `id`, `answers`, `correct`) VALUES
('$name', '$id','$answers','$correct')";
//Run Query
$result = mysql_query($q) or die(mysql_error());
Also, you should avoid using mysql_ functions as they are in the process of being deprecated. Instead, I recommend you familiarize yourself with PDO.
Also, note, the or die(mysql_error()) portion should not be used in production code, only for debugging purposes.
Two things.
You are actually executing the query twice. mysql_query executes the query and returns the result resource. http://php.net/manual/en/function.mysql-query.php
And also, you are quoting the int column correct in your query, as far as I know, you can't do that (I could be wrong there).
$result = mysql_query("INSERT INTO `answer` VALUES (NULL,'$name', '$id','$answers',$correct)");
EDIT: Turns out I'm actually wrong, you may disregard my answer.
I'd like to insert data into a table only when certain values in that table's (sessionid) row match another variable. I am struggling to put together the INSERT statement. The approach I am taking: retrieve all the rows in the table that match the criteria (retailer=$retailer) and then iterate through those rows inputting the variable options into the sessionid table.
$retailer = $_GET['retailer'];
$options = $_GET['options'];
$session = session_id();
//mysql connection stuff goes here
$query = "
SELECT *
FROM `sessionid`
WHERE `retailer` = '$retailer'
";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
mysql_query("INSERT INTO sessionid (options) VALUES('$options')");
}
Is the syntax correct for me to do this? Thanks!
Are you maybe looking for the UPDATE command instead?
UPDATE sessionid
SET options = $options
WHERE retailer = $retailer
By the way, I would look in to using PDO as it's more secure than pushing $_GET values in a database.
$db = new PDO('mysql:host=localhost;dbname=MYDATABASE', 'username', 'password');
$db->prepare('UPDATE sessionid SET options = ? WHERE retailer = ?');
$db->execute(array($options, $retailer));
You can use the WHERE clause in mysql to do this. If you are changing an existing row, you actually want UPDATE, not INSERT.
UPDATE sessionid SET options=$options where retailer = $retailer
Suppose I have a table called "device" as below:
device_id(field)
123asf15fas
456g4fd45ww
7861fassd45
I would like to use the code below to insert new record:
...
$q = "INSERT INTO $database.$table `device_id` VALUES $device_id";
$result = mysql_query($q);
...
I don't want to insert a record that is already exist in the DB table, so how can I check whether it have duplicated record before inserting new record?
Should I revise the MYSQL statement or PHP code?
Thanks
UPDATE
<?php
// YOUR MYSQL DATABASE CONNECTION
$hostname = 'localhost';
$username = 'root';
$password = '';
$database = 'device';
$table = 'device_id';
$db_link = mysql_connect($hostname, $username, $password);
mysql_select_db( $database ) or die('ConnectToMySQL: Could not select database: ' . $database );
//$result = ini_set ( 'mysql.connect_timeout' , '60' );
$device_id = $_GET["device_id"];
$q = "REPLACE INTO $database.$table (`device_id`) VALUES ($device_id)";
$result = mysql_query($q);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
Since I understood well your question you have two ways to go, it depends how you would like to do the task.
First way -> A simple query can returns a boolean result in the device_id (Exists or not) from your database table. If yes then do not INSERT or REPLACE (if you wish).
Second Way -> You can edit the structure of your table and certify that the field device_id is a UNIQUE field.
[EDITED]
Explaining the First Way
Query your table as follow:
SELECT * FROM `your_table` WHERE `device_id`='123asf15fas'
then if you got results, then you have already that data stored in your table, then the results is 1 otherwise it is 0
In raw php it looks like:
$result = mysql_query("SELECT * FROM `your_table` WHERE `device_id`='123asf15fas'");
if (!$result)
{
// your code INSERT
$result = mysql_query("INSERT INTO $database.$table `device_id` VALUES $device_id");
}
Explaining the Second Way
If your table is not yet populated you can create an index for your table, for example go to your SQL command line or DBMS and do the follow command to your table:
ALTER TABLE `your_table` ADD UNIQUE (`device_id`)
Warning: If it is already populated and there are some equal data on that field, then the index will not be created.
With the index, when someone try to insert the same ID, will get with an error message, something like this:
#1062 - Duplicate entry '1' for key 'PRIMARY'
The best practice is to use as few SQL queries as possible. You can try:
REPLACE INTO $database.$table SET device_id = $device_id;
Source