SQL Query give results from wrong table - php

Its very strange. I do a SQL query which works totally fine when he found entries that match. But I tested it with no database entries to show the user "NOTHING TO SHOW" but then it gives me back the complete user row which is in another table and I don't can figure out why this is happening.
my connection
try
{ $db = new PDO("mysql:host={$_MYSQL['host']};
dbname={$_MYSQL['database']}", $_MYSQL['user'], $_MYSQL['pass'], [ PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8", PDO::ATTR_PERSISTENT => true ]);
}
catch (PDOException $e) { exit($e->getMessage());
}
my code
$sql = $db->query("SELECT id, oname, datum, prov FROM completed_tasks WHERE user_id =" .$db->quote($user['id']));
if ($sql->rowCount() != 0) {
$row = $sql->fetchAll();
}
When in completed_task are entries with the user_id it works like expected. When there is nothing to match in table completed_tasks it gives me the complete user row from a totally different table users. So how can this happen?

Code you provided seems to be correct.
It might be, that $row variable is also used somewhere else in your code - maybe before of after snippet you provided. And since this particular query has no rows in the result, content of $row remains the same - so it might contain result from the previous query. It might also be, that it will be overwritten later on.

Related

sqlsrv_execute doesn't return anything

I'm using the SQL Server drivers for PHP to access a SQL Server database and I have a problem to update some data using sqlsrv_prpare and sqlsrv_execute functions.
I'm running two queries:
In the first query I'm retrieving some binary data (In SQL Server Management Studio, this query takes about 15 minutes to getting completed);
Then, for each row returned by the first query execution I'm trying to Update some data on the database.
Here's how my code looks like:
$query1 = "SELECT tgt.id, src.file, src.field1 from [Table1] tgt inner join [Table2] src on tgt.id = src.id order by tgt.id";
$query2 = "UPDATE [Table1] SET field1 = ? WHERE id = ?";
$getFiles = sqlsrv_query($con, $query1); //$con is the connection with the database, received by parameter
while($row = sqlsrv_fetch_array($getFiles, SQLSRV_FETCH_BOTH)) {
/* Some code here */
$file = $row[1];
$value = $row[2];
try {
if(!is_null($file)) {
$stmt = sqlsrv_prepare($con, $query2, array(&$value, &$row[0]));
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
sqlsrv_execute( $stmt );
}
} catch (Exception $e) {
error_log("\nError: " . $e->getMessage());
}
} //end while
sqlsrv_free_stmt($getFiles);
sqlsrv_close($con);
The problem is that the code inside the loop works fine to the first row, but on the second the update query isn't executed. The sqlsrv_prepare returns the value 1, but the sqlsrv_execute doesn't returns anything.
I'm thinking that the problem could be related to the first query execution time, but I don't know how to check this, considering that no error log is generated, the script just keeps executing forever.
EDIT: Actually, the example was simplified. The values that will be updated on tgt table are calculated using some data that are in src table and other application data. That's the reason why I use the loop, for each row returned by query1 specific values are calculated and used on query2. I already checked that these values are correctly calculated, this is why I thought it's better to simplify the example.
To solve this problem I have to ran the queries separately:
First I ran the query1, made the computation of the data that I needed to update the tgt table and stored them in an array;
Then, using the data stored in array, I ran the query2.
No other changes were needed.

How to retrieve data from SQL Server?

I was wondering why my query is returning null when I know there is data there.
my query is as follows:
if (isset($_POST['noteid']))
{
$showNoteInfo = "SELECT Note FROM Notes WHERE NoteID = 2";
$showNotes = sqlsrv_query($conn, $showNoteInfo);
var_dump($showNotes);
}
I have tested $_POST['noteid'] and that displays an ID no problem, in theory this id will replace where I have the number 2 in my query.
However I know in my table in the Notes table where NoteID = 2 the text should be like this
However var_dump displays "resource(7) of type (SQL Server Statement)"
And I have also tried a different method of displaying it and that returned as the query expected resource and was given NULL, so why is this query not getting any results?
My connection details are in an include at the top of the page and are like this: http://pastebin.com/qz3tScdW
If you need anything else please ask.
Underlying question, why is my Query returning NULL when I know theres data there?
You never actually try to retrieve your data. sqlsrv_query performs the database query, but it doesn't get the data. You need to use sqlsrv_fetch_array (or sqlsrv_fetch_object) for that:
$stmt = sqlsrv_query($conn, $showNoteInfo);
if (sqlsrv_has_rows($stmt)) {
$data = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC);
var_dump($data['Note']);
} else {
echo "No data found";
}

PDO Insert Query Not Working For Integer

I have this code to insert a new row into MySQL DB using PDO:
$query = INSERT INTO asset_positions (pos_asset_id, pos_latitude, pos_longitude, pos_timestamp) VALUES (:pos_asset_id, :pos_latitude, :pos_longitude, :pos_timestamp)
$statement = $pdo->prepare($query);
$array = [':pos_asset_id' => 1, ':pos_latitude' => -8.5, ':pos_longitude' => 125.5, ':pos_timestamp' => 1398160487];
$statement->execute($array);
echo $pdo->lastInsertId();
The query runs without any error shown. The newly inserted row ID is echoed. However, when i look in the DB, it only insert the latitude, longitude and timestamp. The pos_asset_id field in the newly inserted row is empty.
Could somebody point out where is the problem? There is no error message displayed. I've been trying to solve this for hours without avail.
Ps. This is my first time using PDO, so please bear with me. Thanks.
EDIT
Solved! I didn't notice that there's a FK relation between asset_positions.pos_asset_id and asset.asset_id. Once i remove this relationship constrains, the INSERT works properly now, the pos_asset_id value is inserted to the record.
Anyway, thanks all! :)
try running with error catching, it will give you better understanding of what is happening.
try {
$stmt->execute();
} catch (PDOException $p) {
echo $p->getMessage();
} catch (Exception $e) {
echo $e->getMessage();
}
But your common sense and user3540050 are right... it's a column related issue probably

PDO Update with variable table, column, row

I would like to build an ajax function that updates field variables in some tables.
The tables, fields, and rows are all variable and based on what is posted via the ajax function.
This is the code for my quickedit.php
define( "DB_DSN", "mysql:host=$host;dbname=$data" );
define( "DB_USERNAME", $user );
define( "DB_PASSWORD", $pass );
if(isset($_POST['table'])){ $table = $_POST['table'];}
if(isset($_POST['id'])){ $id = $_POST['id'];}
if(isset($_POST['field'])){ $field = $_POST['field'];}
if(isset($_POST['value'])){ $value = $_POST['value'];}
try {
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
} catch (Exception $e) {
die("Connection Error");
}
try {
$st = $con->prepare("UPDATE :table SET :field = :value WHERE id = :id");
$st->execute(array(':table'=>$table, ':id'=>$id, ':field'=>$field, ':value'=>$value));
} catch (Exception $e) {
die("Query Error");
}
echo "table: ".$table." id: ".$id." field: ".$field." value: ".$value;
As you can see, I wish to dynamically select the table, column, and row.
I'm don't know a whole lot about exceptions, but none of them are being thrown
and it is successfully echoing the stuff at the bottom i told it to.
As you can see, I wish to dynamically select the table, column, and row.
Yes, we see it.
And this is where your idea is wrong.
This is quite contagious disease every good programmer have to outgrow. You are trying to make Universal Updater. Unfortunately, although the idea of some automation is usually all right, too much automation can be a disaster.
Your application have to have an idea what does it update and why. All the queries have to be pre-written and only data part may vary. It's all right to build a dynamical update from the several fields, but makeing even table name dynamical is too much.
As of your particular problem, ORM is what you really looking for. Look how it can be done with Yii Active record:
$post=$table::model()->findByPk($id);
$post->$field=$value;
$post->save(); // save the change to database
You'll need to build the original mysql sentence in the old way, using PHP to evaluate table and column names. Then use PDO to bind values to the fields.
$st = $con->prepare("UPDATE $table SET $field = :value WHERE id = :id");
$st->bindValue(':id',$id,PDO::PARAM_INT);
$st->bindValue(':value',$value,PDO::PARAM_STR);
$st->execute();
Be carefult not to allow quotes or semicolons in the variables youre evaluating. It's fairly easy to perform an SQL injection that way.

How do I loop through a mysql query with php

I tried to use this function
$conn = db_connect();
while ($newsfeed = $conn->query("select info, username, time from newsfeed ORDER BY time DESC LIMIT 10"))
{
(...)
echo "<p>User $newsfeed_username just registerted ".$minutes." min ago </p><br>";
but it only shows the latest row over and over again. I want to loop through all the queries from
select info, username, time from newsfeed ORDER BY time DESC LIMIT 10
in descending order.
Here's the basic template for this kind of thing, using built-in php functions (assuming old-style mysql, but similar using other database back-ends, or higher-level libraries). In this example, errors are handled by throwing exceptions, but that's just one way to do it.
Connect to the database
Make sure connection was successful
Run the query
Make sure the query didn't fail for some reason (usually a SQL syntax error). If it did fail, find out why and handle that error
Check that the query returned at least one row (zero rows typically is a special case)
Loop over the returned rows, doing whatever it is you need done.
The exception classes would need to be defined (they're the only non-built-in syntax here, but you shouldn't throw plain-vanilla Exceptions).
Example Code:
<?PHP
//try to connect to your database.
$conn = mysql_connect(...);
//handle errors if connection failed.
if (! $conn){
throw new Db_Connect_Error(..);
}
// (try to) run your query.
$resultset = mysql_query('SELECT ...');
//handle errors if query failed. mysql_error() will give you some handy hints.
if (! $resultset){
// probably a syntax error in your SQL,
// but could be some other error
throw new Db_Query_Exception("DB Error: " . mysql_error());
}
//so now we know we have a valid resultset
//zero-length results are usually a a special case
if (mysql_num_rows($resultset) == 0){
//do something sensible, like tell the user no records match, etc....
}else{
// our query returned at least one result. loop over results and do stuff.
while($row = mysql_fetch_assoc($resultset)){
//do something with the contents of $row
}
}
First you don't want to loop though queries. You want to loop through records which query will return.
Second you could do that, this way:
$conn = db_connect();
$query = mysql_query("SELECT info, username, time FROM newsfeed ORDER BY time DESC LIMIT 10");
while(($row = mysql_fetch_assoc($query)) != NULL) {
echo "<p>User {$row['username']} just registered {$minutes} min ago</p><br />";
}
NB! Assuming, that this db_connect() makes a mysql connection.
You need to store the result of $conn-query() in a variable before entering the loop. Right now you're running the query over and over again with each iteration of the loop which will always give you the first result.
Example
$conn = db_connect();
$result = $conn->query("select info, username, time from newsfeed ORDER BY time DESC LIMIT 10");
foreach ($result as $newsfeed)
{
(...)
echo "<p>User $newsfeed_username just registerted ".$minutes." min ago </p><br>";

Categories