I am doing work with php object oriented and mysqli. i have class name Database.php inside this class i have defined a function name update.
i did some thing wrong i think that's why it doesn't work fine. when i use to run click at update then data retrieves in Form but when i try to save the updated form it always updated only first column of my database. function code is given below:
public function update($tablename, $value, $where){
$Update = " UPDATE ".$tablename." SET ";
$array_keys = array_keys($value);
$array_values= array_values($value);
$count = count($array_keys);
for($i=0; $i< $count; $i++){
$value[$i] = " = '".$value[$array_keys[$i]]."' ";
}
//$value = implode(" ",$value);
print_r($value);
$Update .= " ".$value." WHERE ".$where;
$Utest = $this->DbCon->query($Update);
if($Utest){
return true;
}else{
return false;
}
here is php code that i have tried before
if(isset($_POST['update'])){
$id1 = $_POST['id'];
$name = $_POST['name'];
$city = $_POST['city'];
$success=$DbQuery->update("record", array(" name " => $name ,"city" => $city)," id =".$id1);
if($success){
header("LOCATION:index.php");
}else{
echo "try again ";
}
}
do you have any good suggestion for update function how ic an improve this function. actually i am new in php object oriented so suggest me easy method to this. Thanks
The problem is that you're trying to convert the $value array to a string in $Update .= " ".$value." WHERE ".$where;. You can't do that. You have to construct the query in the for loop above it instead of populating the $value array. Either way you shouldn't be building the query by hand. You REALLY should use PDO::prepare() or $mysqli::prepare() to prevent vulnerabilities. Yes, that might feel like an overkill if you're just learning, but you should start forming good habits from the very beginning.
Also, fix your formatting. Your code is really hard to read. I recommend reading through the PSR standard (or any widespread PHP standard) and adapting it in your code. Again, might feel like overkill, but it's a good habit to pick up early.
Here's an adapted version of your code for you to easily play with. You can see the problem if you run php index.php in the CLI window at the bottom.
Related
I am sure that this question has been asked before, but I am unable to come up with the proper keywords (especially in english).
I am using PHP and I am trying to for loop through a parameter of a function. So the function should be called, store the retrieved data in some variables and these variables should then be inserted into a database.
However, the loops only runs once! If I substitute $id with any number it works fine, but only once.
This is a simplified version of my code:
for ($i=0; $i<9; $i++) {
$id = $rows[$i][1];
$values = getDetails($id); // This function (from another file) returns an array
$title = $values["Title"];
$year = $values["Year"];
$query= " INSERT INTO database
VALUES ('','$title','$year')";
$result = $mysqli->query($query);
}
* EDIT This is part of the getDetails function:
function getDetails($id) {
$url = "http://www.something.de/". $id . "/";
$html = file_get_html ( $url );
$title = $html->find('span[itemprop=name]');
$title = explode('>',$title[0]);
$title = explode('</span',$title[1]);
... // This might look weird and is definatly not perfect, but it works :)
$details = array("Title" => $title[0], "Year" => $year[1]);
return $details;
}
* EDIT
WOW! I found the reason ... I had a function within my function which was never used. I just commented it out and my code works just fine. I assume it is not a good idea to so anyways.
I think your $query is wrong.
Change this:
$query= " INSERT INTO database
VALUES ('','$title','$year')";
To something like this:
$query= " INSERT INTO database (field1,field2,field3)
VALUES ('','$title','$year')";
Is your ID field autoincrementing? If so you do not need the "field1" entry at all.
Happy Coding!
I had this problem also.
I could print to a table without a problem the parameters I was feeding into a function in a loop. But the function calls in the loops would only call once.
SOLUTION: Remove the location redirects and the exit(); from the function.
Hope this helps someone else.
I have large tables in my database and instead of specifying each column name I am trying to build the query dynamically.
I am trying to do an update in the 'motherboard' table based on the POST data received. The $data object i receive has more fields than the table has. (I added some fields for some flags.)
Hence, I am retrieving the record I'm about to update and by comparing each of it's columns with my $data object fields I am constructing the UPDATE query.
I'm new to php, therefore I don't know the syntax well.
This is the code:
<?php
$data = json_decode($_POST["data"], true);
$id = $data["ID"];
include_once 'dbconnect.php';
$query = sprintf("SELECT * FROM `motherboard` WHERE ID = " . $id . ";");
$result = mysqli_query($con, $query);
$existingData = mysqli_fetch_assoc($result);
include_once 'dbclose.php';
$statement = "";
$statement = "UPDATE motherboard SET ";
$flag = false;
foreach ($existingData as $key => $value) {
if ($existingData->$key != $data->$key) {
$statement .= $key . " = " . $data->$key . " , ";
$flag = true;
}
}
if ($flag)
$statement = substr($statement, 0, strrchr($statement, ',') - 1);
$statement .= " WHERE ID = " . $id . ";";
echo $statement;
?>
My main problem is in the foreach loop. I don't know how can I compare and then use for building the query the $existingData and $data variables.
How can I achieve this?
Don't use this approach please, if you want a SOLID application that will outrun the ages, use specific column names and not some junkish foreach loop that builds your SQL for you. If you want to evade the writting of SQL, use an ORM, there are ton's that exist out there and most of them are bundled with a framework right off the start making it simpler to learn the ropes!
Examples of simple to learn frameworks: (But not necessarely weak frameworks)
Cake PHP
Laravel
Good luck
You need to change some code ...
$result = mysqli_query($con, $query);
$existingData = mysqli_fetch_assoc($result);
Now your $existingData is an array you can loop though;
Honestly I would recommend you take advantage of a framework with an ORM or just a standalone ORM. I suggest Laravel or CodeIgniter (if you are new to programming in general then CodeIgniter will be the easiest).
Next, why is your POST data JSON encoded? Why not just POST all the form variables? I would recommend that way instead to simplify it (even from JS).
Finally, you have to make sure you sanitize your inputs. You can use mysqli_real_escape_string(). I am assuming you will use the MySQLi DB interface. (Ref: http://php.net/manual/en/mysqlinfo.api.choosing.php)
Actually one last note: Laravel is, in my opinion, the future of PHP frameworks. It is beautiful, lightweight, and powerful. I HIGHLY recommend that you learn it. Ref: http://laravel.com/
I managed to get it working. Now I'm constructing my queries based on the difference between the existing data and the updates from the user. The foreach loop now looks like this:
foreach ($existingData as $key => $value) {
if ($existingData[$key] != $data[$key]) {
$statement .= $key . " = \"" . $data[$key] . "\" , ";
$flag = true;
}
}
This is the part that was interesting for me. The rest of the code should be updated according to the latest API.
I am really trying to wrap my head around this and failing miserably. What I want to do it build a MySQL query based on the URL parameters passed by the URL. I am trying to create a re usable dynamic script that can do what it needs to do based on the URL parameter.
This is what I have come up with, and it appears that it does what it is supposed to do (no errors or anything) but nothing actually gets inserted in the database. I know somewhere I have made a dumb mistake (or thought something out wrong) so hopefully one of you guys can point me in the right direction.
Thanks!
//List all possible variables you can expect the script to receive.
$expectedVars = array('name', 'email', 'score', 'age', 'date');
// This is used for the second part of the query (WHERE, VALUES, ETC)
$fields = array('uName','uEmail','uScore','uAge','uDate');
// Make sure some fields are actually populated....
foreach ($expectedVars as $Var)
{
if (!empty($_GET[$Var]))
{
$fields[] = sprintf("'%s' = '%s'", $Var, mysql_real_escape_string($_GET[$Var]));
}
}
if (count($fields) > 0)
{
// Construct the WHERE Clause
$whereClause = "VALUES " . implode(",",$fields);
//Create the SQL query itself
$sql = ("INSERT INTO $mysql_table ($fields) . $whereClause ");
echo "1"; //It worked
mysql_close($con);
}
else
{
// Return 0 if query failed.
echo "0";
}
?>
You missed mysql_query($sql):
if(!mysql_query($sql)){
//die(mysql_error());
}
Please consider to use PDO or My SQLi using parametrize query because mysl_* function depreciated.
Your SQL is all wrong. You're using the field = value syntax for an INSERT, then you're concatenating an array as if it were a string ($fields), and you're missing a couple of parentheses around the values.
a couple of things: i've found for php <-> mysql its important to see what's going into mysql and experiement directly with those queries in phpmyadmin when i get stuck.
1 - in my code I output mysql_error() when the query fails or when a debug flag is set. this usually explains the sql issue in a way that can point me to a misspelled field name etc...
2 - this way i can feed that mysql query directly into phpmyadmin and tweak it until it gives me the results i want. (while i'm there i can also use explain to see if i need to optimize the table)
specifics in your code. unlike C languages sprintf is implied. here's how i'd write your code:
// List all possible variables you can expect the script to receive.
$expectedvars = array('name', 'email', 'score', 'age', 'date');
// This is used for the second part of the query (WHERE, VALUES, ETC)
// $fields = array('uName','uEmail','uScore','uAge','uDate');
$fields = array();
// Set only the variables that were populated ...
foreach ($expectedvars as $var) {
if (!empty($_GET[$var])) {
$name = "u" + ucwords($var); // convert var into mysql field names
$fields[] = "{$name} = " . mysql_real_escape_string($_GET[$var]);
}
}
// only set those fields which are passed in, let the rest use the mysql default
if (count($fields) > 0) {
// Create the SQL query itself
$sql = "INSERT INTO {$mysql_table} SET " . implode("," , $fields);
$ret = mysql_query($sql);
if (!$ret) {
var_dump('query_failed: ', $sql, $ret);
echo "0"; // Query failed
} else {
echo "1"; // It worked
}
} else {
// Return 0 if nothing to do
echo "0";
}
mysql_close($con);
How can I pull multiple rows from a database using a function?
The function I have is:
function search($subject, $table) {
$query = "SELECT {$subject} ";
$query .= "FROM {$table} ";
$content = mysql_query($query);
return $content;
}
On the page which is calling the function I have:
if (isset($_POST['search'])){
$search = $_POST['search'];
}
$content = search($subjectName, $tableName);
while ($results = mysql_fetch_assoc($content)){
$phrase = $results[$subjectName];
//if phrase exists in database
if (strpos($search,$phrase) !== false) {
echo $phrase;
//if phrase does not exist in database
} else {
echo 'fail';
}
This setup does not work, however if I put everything into the function it works:
function search($subject, $table, $where = 0, $is = 0) {
global $search;
$query = "SELECT {$subject} ";
$query .= "FROM {$table} ";
if ($where > 0) {
$query .= "WHERE {$where} = '{$is}' ";
}
$content = mysql_query($query);
while ($results = mysql_fetch_assoc($content)){
$phrase = $results[$subject];
//if phrase exists in database
if (strpos($search,$phrase) !== false) {
echo $phrase;
//if phrase does not exist in database
} else {
echo 'fail';
}
}
return $content;
}
On Page:
search('main_subject', 'main_search');
The problem is that I would like to call that function again in the if statement to have it search for another phrase. Is there an easier way to do this?
EDIT: The current setup pulls the first item in an infinite loop.
There are a number of issues that should be addressed here:
First, if you are trying to search a field for a specific partial match, you would likely want to use SQL LIKE construct.
SELECT field FROM table WHERE field LIKE '%search phrase%'
Doing this would eliminate the need for you to iterate through each row trying to do a string comparison for your search phrase, as you would only be returned the rows that match the search phrase and nothing more.
Second, using global to make data available to your function is really poor practice. You really should be passing any data needed by the function to the function as a parameter. This would include your search string and probably your database connection/object.
function search($field, $table, $search, $db) {
...
}
Third, You are doing nothing at all to prevent against SQL injection right now. You need to escape the input data or, better yet use prepared statements.
Fourth, you really should not be using the mysql_* functions. They are deprecated. Try using mysqli or PDO (and I would highly recommend going ahead and learning how to use prepared statements with either of these.) You might start with mysqli ,at it provide procedural functions similar to mysql_* so the learning curve might be less steep (though really most experienced developers would prefer the object-oriented usage).
Fifth, to your original question. If you want search for multiple phrases, there are a couple approaches you can take. You can either pass all the phrases at once like this:
SELECT field FROM table WHERE field LIKE '%search phrase%' OR field LIKE '%another search phrase%'
Or, you could just make iterative function calls to get the results you want. This really depends on whether you only want to search for the second phrase if the first is not successful (use the iterative approach) or whether you just want all possible matches in one query (use the LIKE-OR-LIKE approach).
Hey guys, i'm currently learning php and I need to do this
$connection = mysql_open();
$likes= array();
foreach($likes as $like)
{
$insert3 = "insert into ProfileInterests " .
"values ('$id', '$like', null)";
$result3 = # mysql_query ($insert3, $connection)
or showerror();
}
mysql_close($connection)
or showerror();
For some reason this does not work =/ I don't know why. $likes is an array which was a user input. I need it to insert into the table it multiple times until all of the things in the array are in.
EDIT I fixed the issue where I was closing it in my foreach loop. mysql_open is my own function btw.
Any ideas?
For one $likes is an empty array in your example, I am assuming you fix that in the code you run.
The second is you close the MySQL connection the first the time the loop would run, which would prevent subsequent MySQL queries from running.
there's no such function as mysql_open
you may need mysql_connect
also $likes variable is empty. so no foreach iterations will execute.
You close the connection within the foreach loop.
Here is the proper formatted code to insert data...You can use this.
// DATABASE CONNECTION
$conn=mysql_connect(HOST,USER,PASS);
$link=mysql_select_db(DATABASE_NAME,$conn);
// function to insert data ..here $tableName is name of table and $valuesArray array of user input
function insertData($tableName,$valuesArray) {
$sqlInsert="";
$sqlValues="";
$arrayKeys = array_keys($valuesArray);
for($i=0;$i < count($arrayKeys);$i++)
{
$sqlInsert .= $arrayKeys[$i].",";
$sqlValues .= '"'.$valuesArray[$arrayKeys[$i]].'",';
}
if($sqlInsert != "")
{
$sqlInsert = substr($sqlInsert,0,strlen($sqlInsert)-1);
$sqlValues = substr($sqlValues,0,strlen($sqlValues)-1);
}
$sSql = "INSERT INTO $tableName ($sqlInsert) VALUES ($sqlValues)";
$inser_general_result=mysql_query($sSql) or die(mysql_error());
$lastID=mysql_insert_id();
$_false="0";
$_true="1";
if(mysql_affected_rows()=='0')
{
return $_false;
}
else
{
return $lastID;
}
}
// End Of Function
While many PHP newbies (myself included) begin working with databases from good ole' mysql_connect/query/etc., I can't help suggest that you look into PDO, PHP Data Objects. Depending on your prior knowledge and programming background, there may be a steeper learning curve. However, it's much more powerful, extensible, etc.; I use PDO in all my production code database wheelings-and-dealings now.