I need help. I need to get the result of a update sql query using doctrine 1.2
I googled and I found a way to make a native sql query using doctrine
$preparequerystring = "UPDATE mdw_reportes_operacion SET mmaplicado = 2.742495126705653 WHERE id = 5294;";
$con = Doctrine_Manager::getInstance()->connection();
$st = $con->executeUpdate($preparequerystring,array(false));
print_r($st);
I would like to know how to retrieve some information about the query I'm executing. I've tried with
$result = $st->fetch();
but it returns a 500 internal server error.
What is the right way to retrieve information about the query when performing an UPDATE query?
Why not using the default update from doctrine instead of a row sql ?
$q = Doctrine_Query::create()
->update('MdwReportesOperacion')
->set('mmaplicado', '2.742495126705653')
->where('id = ?', array(5294));
$rows = $q->execute();
echo $rows;
Edit:
I didn't know how to retrieve the result from a raw doctrine query, but you still can use pdo query:
// update the way you want to retrieve database information
$database = sfYaml::load(dirname(__FILE__).'/../config/databases.yml');
$param = $database['all']['doctrine']['param'];
$conn = new PDO($param['dsn'], $param['username'], $param['password']);
// and then perform the query and retrieve the result
$rows = $conn->exec("UPDATE mdw_reportes_operacion SET mmaplicado = 2.742495126705653 WHERE id = 5294;");
echo $rows;
Related
I want an if-statement that only runs, when there are no rows in the table or if existing rows dont match a specific parameter from my input. I tried this way:
$currentURL = $post["media_url"];
$sql = "SELECT * FROM images WHERE imageURL = '$currentURL'";
$result = $conn->query($sql);
if(!$result)
{ ... }
From my thinking this should execute the if-statement on the first time I want to add something to the database and if the $currentURL does not exist in existing data. But this does not seem to work the way I think it does. How would you do this? Maybe I'm handling the $result wrong, because if I test the sql-query inside phpmyadmin this shows the right result (no rows).
The correct way to do this would be to use prepared statement and fetch the results into an array. You can fetch all rows into an array using fetch_all()
$stmt = $conn->prepare("SELECT * FROM images WHERE imageURL = ?");
$stmt->bind_param('s', $post["media_url"]);
$stmt->execute();
// Get result and then fetch all rows from the result object
$result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
// Then check if you have any rows at all using a simple if statement
// Negate it using ! to check if the array is empty
if (!$result) {
// no results found
}
I guess, that $conn is a PDO connection? In that case, the method $conn->query() returns an object of type PDOStatement. See https://www.php.net/manual/de/class.pdostatement.php
The method does NOT return the result set.
Instead you can use the PDOStatement object, to fetch the results:
$currentURL = $post["media_url"];
$sql = "SELECT * FROM images WHERE imageURL = '$currentURL'";
$result = $conn->query($sql)->fetchAll();
if(empty($result))
{ ... }
In case you are using mysqli, the object returned by query() is this: https://www.php.net/manual/en/class.mysqli-result.php
So the code would be:
$currentURL = $post["media_url"];
$sql = "SELECT * FROM images WHERE imageURL = '$currentURL'";
$result = $conn->query($sql)->fetch_all(MYSQLI_ASSOC);
if(empty($result))
{ ... }
Please also note: Your code is highly insecure! You should use prepared statements to prevent sql-injection:
$currentURL = $post["media_url"];
$sql = "SELECT * FROM images WHERE imageURL = :currentUrl";
$stmt = $conn->prepare($sql);
$stmt->execute(['currentUrl' => $currentURL]);
$result = $stmt->fetchAll();
if(empty($result))
{ ... }
sanitize input against sql injection (or better - use prepared statements and param binding)
$sql = "SELECT * FROM images WHERE imageURL = '".$conn->real_escape_string($currentURL)."'";
mysqli query returns true on success (even empty dataset is success), use num_rows instead:
if ( $result->num_rows === 0 ) { ... }
This is my first time to try PDO and still learning it. I am more familiar in using mysql or mysqli in developing php system.
After deep searching and searching I still can't seem to understand how to query using PDO
In my code I used mysqli inside a function to be called in index.php
function getUsery(){
$ip = getIPAddress();
$query = mysqli_query("select userID from tblUsers where logged='1' AND ip='$ip'");
$row = mysqli_fetch_array($query);
$emp = $row['userID'];
$logged = $row['logged'];
$userlvl = $row['userLevel'];
$_SESSION['logged'] = $logged;
$_SESSION['userLevel'] = $userlvl;
return $emp;
}
I don't really know how to select sql query using PDO with 'where' statement. Most of what I found is using array with no 'where' statement
How can I select the userID where logged is equal to '1' and ip is equal to the computer's ip address and return and display the result to the index.php
There's SQL statement with WHERE in PDO
$sql = "SELECT * FROM Users
WHERE userID = ?";
$result = $pdo->prepare($sql);
$result->execute([$id]);
Assuming that you know how to connect database using PDO, here is how to select SQL with PDO.
$stmt = $db->prepare("select userID from tblUsers where logged = '1' AND ip = :ip");
$stmt->execute(array('ip' => $ip));
$listArray = $stmt->fetchAll();
Notice the :ip at the end of SELECT. If you don't use ? as a parameters, the prefix : is mandatory and the word after that should be the same as the key in the execute function.
EDIT
In case that the above code is inside the function and $db is outside the function, declare $db as global variable inside the function.
This one is imo one of best guides on PDO and how to use it:
https://phpdelusions.net/pdo
WHERE is a part of query and queries in PDO are not much different from pure *sql queries, just there is going on a bit filtering on execution. Read the guide carefully and you will be able to execute any query you need to.
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 am so sorry mybe it is a silly question but as I am new in web language and php I dont know how to solve this problem.
I have a code which is getting ID from user and then connecting to MySQL and get data of that ID number from database table and then show on webpage.
But I would like to what should I add to this code if user enter an ID which is not in table of database shows a message that no data found.
Here is my code:
<?php
//connect to the server
$connect = mysql_connect ("localhost","Test","Test") ;
//connection to the database
mysql_select_db ("Test") ;
//query the database
$ID = $_GET['Textbox'];
$query = mysql_query (" SELECT * FROM track WHERE Code = ('$ID') ");
//fetch the results / convert results into an array
$ID = $_GET['Textbox'];
WHILE($rows = mysql_fetch_array($query)) :
$ID = 'ID';
echo "<p style=\"font-color: #ff0000;\"> $ID </p>";
endwhile;
?>
Thank You.
Sorry if it is so silly question.
You should use PDO (great tutorial here: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers ). This way, you can develop safer applications easier. You need to prepare the ID before inserting it to the query string, to avoid any user manipulation of the mysql query (it is called sql injection, guide: http://www.w3schools.com/sql/sql_injection.asp ).
The main answer to your question, after getting the results, you check if there is any row in the result, if you got no result, then there is no such an ID in the database. If you use PDO statements $stmt->rowCount();.
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$stmt = $db->prepare("SELECT * FROM table WHERE Code=?");
$stmt->bindValue(1, $id, PDO::PARAM_INT); // or PDO::PARAM_STR
$stmt->execute();
$row_count = $stmt->rowCount();
if ($row_count > 0) {
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
//results are in $results
} else {
// no result, no such an ID, return the error to the user here.
}
Another reason to not use mysql_* functions: http://php.net/manual/en/migration55.deprecated.php
This is my first time using symfony 2. For database integration i am thinking of using propel as I doctrine and annotations seems really difficult for me. But it seems to me that to make a query you have to use propels own functions. I have used codeigniter. In codeigniter I used to send query string and it used to send me data. Is there something similar in propel symfony 2?
Like -
$query = 'select * from table where column1 natural join column2';
$this->db->query($query);
You should look at docs of sf2:
http://symfony.com/doc/current/book/propel.html
If you want to use raw SQL:
$em = $this->getDoctrine()->getEntityManager();
$connection = $em->getConnection();
$statement = $connection->prepare("SELECT something FROM somethingelse");
$statement->execute();
$results = $statement->fetchAll();
Or "propel way":
$connection = Propel::getConnection();
$query = 'SELECT MAX(?) AS max FROM ?';
$statement = $connection->prepareStatement($query);
$statement->setString(1, ArticlePeer::CREATED_AT);
$statement->setString(2, ArticlePeer::TABLE_NAME);
$resultset = $statement->executeQuery();
$resultset->next();
$max = $resultset->getInt('max');