I'm trying to submit an update function, but for some reason it's not working and I can't figure out why... Someone who does?
UPDATE SQL-SYNTAX:
public function updateProject($db, $id) {
$sql = "UPDATE tblProject SET
name = '".$db->escape($this->name)."',
photo1 = '".$db->escape($this->photo1)."'
WHERE id = '".$id."'";
return $db->insert($sql);
}
INSERT FUNCTION:
public function insert($sql) {
mysql_query($sql, $this->_connection);
return mysql_affected_rows($this->_connection);
}
PHP:
$project = new Project();
$project->name = $_POST['newproject_name'];
$project->photo1 = $_FILES['images']['name'][0];
if($project->updateProject($_DB, $projectname)) {
$feedback = "OK!";
} else {
$feedback = "NOT OK!!";
}
And in case you were wondering, $project->name and $project->photo1 are filled in correctly.
Any ideas? I hope I gave you everything you need, if not, let me know!
EDIT 1: I used the 2 first answers, but no results. Yet...
EDIT 2: I also don't get anything from $feedback
It looks like you have a stray opening parenthesis after the SET keyword. Remove it.
public function updateProject($db, $id) {
$sql = "UPDATE tblProject SET
name = '".$db->escape($this->name)."',
photo1 = '".$db->escape($this->photo1)."'
WHERE id = '".$id."'";
return $db->insert($sql);
}
public function updateProject($db, $id)
requires 2 parameters being passed but when you do
if($project->updateProject($_DB))
you're only passing 1??
Your updateProject needs two variables and the second one is missing in your call, resulting in an invalid query.
Edit: Based on your edit; I'm guessing $id needs to be an integer or a string, you are passing an object.
Exactly what row do you want to update? I don't see anything in your php code that defines the ID of the row you want to modify, you are just generating a new object, not getting one from a database for example.
Related
I would like to UPDATE the seat_status to active by checking two conditions.
1st condition = bus_id
2nd condition = seat_title
I'm using this code in function cancelbook.
function cancelbook($conn,$id,$busid)
{
$stmtgetseats = $conn->prepare("SELECT seat_no from tbl_seats WHERE bus_id=:bus_id");
$stmtgetseats->bindParam(':bus_id',$busid);
$stmtgetseats->execute();
$seat_no=$stmtgetseats->fetchAll();
for($i=0;$i<count($seat_no);$i++)
{
$stmtactive = $conn->prepare("UPDATE tbl_busseats SET seat_status='active' WHERE bus_id=:bus_id AND seat_title=:seat_title");
$stmtactive->bindParam('bus_id',$busid);
$stmtactive->bindParam('seat_title',$seat_no[$i]);
}
if ($stmtactive->execute()) {
exit();
return true;
}
return false;
}
im getting this error
Notice: Array to string conversion
The way you did the loop will only update one row, to update every row you should execute your statement for each iteration.
function cancelbook($conn,$id,$busid)
{
$stmtgetseats = $conn->prepare("SELECT seat_no from tbl_seats
WHERE bus_id=:bus_id");
$stmtgetseats->bindParam(':bus_id',$busid);
$stmtgetseats->execute();
$seat_no=$stmtgetseats->fetchAll();
foreach($seat_no as $seat) {
$stmtactive = $conn->prepare("UPDATE tbl_busseats SET seat_status='active'
WHERE bus_id=:bus_id
AND seat_title=:seat_title");
$stmtactive->bindParam('bus_id',$busid);
$stmtactive->bindParam('seat_title',$seat['seat_no']);
$stmtactive->execute();
}
}
it seems $seat_no[$i] is not string and it's an array , (I suggest var_dump($seat_no[$i]); it before), my quess is it should be something the following snippet:
use
$stmtactive->bindParam('seat_title',$seat_no[$i]['seat_no']);
instead of
$stmtactive->bindParam('seat_title',$seat_no[$i]);
in your code will resolved your problem.
of course, it's better instead of using for learn to use foreach
But another solution with better performance is using just one update instead of serveral updates!!!
function cancelbook($conn,$id,$busid)
{
$stmtgetseats = $conn->prepare("SELECT seat_no from tbl_seats
WHERE bus_id=:bus_id");
$stmtgetseats->bindParam(':bus_id',$busid);
$stmtgetseats->execute();
$seat_no=$stmtgetseats->fetchAll();
$seat_numbers = array_values($seat_no);
$stmtactive = $conn->prepare("UPDATE tbl_busseats SET seat_status='active'
WHERE bus_id=:bus_id
AND seat_title IN (:seat_title"));
$stmtactive->bindParam('bus_id',$busid);
$stmtactive->bindParam('seat_title',implode(",",$seat_numbers));
$stmtactive->execute();
}
Also, remove Exit in your code, it's a bad mistake in your code
I'm new in programming and especially with php and MySQL. I have to create dynamic web site for homework. My problem is with the function below. I want it to return int value of tag by given tag name (string). But in my case the function returns every time '1'. Can anyone help me to solve this problem, thanks.
public function getTagIdByName(string $tagName) : int
{
$statement = self::$db->prepare("SELECT tags.id FROM tags WHERE tags.name = ? ");
$statement->bind_param("s", $tagName);
$result = $statement->execute();
return $result;
}
The problem is that you're returning the result of execute(), but that function doesn't actually give you your query result. You need to fetch results after making sure the execution was successful.
//don't forget to error-check before using query results
$statement->execute() or die($statement->error);
$result = $statement->get_result(); //retrieve results for processing
if(!$result->num_rows) return null;//if the id was not found in the DB
else return $result->fetch_assoc()['id'];
You can achieve easily with
$data = $result->fetch_assoc();
return $data['id']; // you can change with which you want to return with field name
And whichever you can use your returned values.
hello i want to create function with returning data, for example when i have the function advert i want to make it every time show what i need, i have the table id, sub_id, name, date, and i want to create the function that i can print every time what i need advert(id), advert(name), i want to make it to show every time what i need exactly and i want to save all my result in array, and every time grab the exactly row that i want
<?php
function advert($data){
$id = $_GET['id'];
$query = mysql_query("SELECT *FROM advertisement WHERE id = $id");
while($row = mysql_fetch_assoc($query)){
$data = array(
'id' => $row['id']
);
}
return $data;
}
echo advert($data['id']);
?>
but my result every time is empty, can you help me please?
There are so many flaws in this short piece of code that the only good advice would be to get some beginners tutorial. But i'll put some effort into explaining a few things. Hopefully it will help.
First step would be the line function advert($data), you are passing a parameter $data to the method. Now later on you are using the same variable $data in the return field. I guess that you attempted to let the function know what variable you wanted to fill, but that is not needed.
If I understand correctly what you are trying to do, I would pass in the $id parameter. Then you can use this function to get the array based on the ID you supplied and it doesnt always have to come from the querystring (although it could).
function advert($id) {
}
Now we have the basics setup, we want to get the information from the database. Your code would work, but it is also vulnerable for SQL injection. Since thats a topic on its own, I suggest you use google to find information on the subject. For now I'll just say that you need to verify user input. In this case you want an ID, which I assume is numeric, so make sure its numeric. I'll also asume you have an integer ID, so that would make.
function advert($id) {
if (!is_int($id))
return "possible SQL injection.";
}
Then I'll make another assumption, and that is that the ID is unique and that you only expect 1 result to be returned. Because there is only one result, we can use the LIMIT option in the query and dont need the while loop.
Also keep in mind that mysql_ functions are deprecated and should no longer be used. Try to switch to mysqli or PDO. But for now, i'll just use your code.
Adding just the ID to the $data array seems useless, but I guess you understand how to add the other columns from the SQL table.
function advert($id) {
if (!is_int($id))
return "possible SQL injection.";
$query = mysql_query("SELECT * FROM advertisement WHERE id = $id LIMIT 1");
$row = mysql_fetch_assoc($query);
$data = array(
'id' => $row['id']
);
return $data;
}
Not to call this method we can use the GET parameter like so. Please be advised that echoing an array will most likely not give you the desired result. I would store the result in a variable and then continue using it.
$ad = advert($_GET['id']);
if (!is_array($ad)) {
echo $ad; //for sql injection message
} else {
print_r($ad) //to show array content
}
Do you want to show the specific column value in the return result , like if you pass as as Id , you want to return only Id column data.
Loop through all the key of the row array and on matching with the incoming Column name you can get the value and break the loop.
Check this link : php & mysql - loop through columns of a single row and passing values into array
You are already passing ID as function argument. Also put space between * and FROM.
So use it as below.
$query = mysql_query("SELECT * FROM advertisement WHERE id = '".$data."'");
OR
function advert($id)
{
$query = mysql_query("SELECT * FROM advertisement WHERE id = '".$id."'");
$data = array();
while($row = mysql_fetch_assoc($query))
{
$data[] = $row;
}
return $data;
}
Do not use mysql_* as that is deprecated instead use PDO or MYSQLI_*
try this:
<?php
function advert($id){
$data= array();
//$id = $_GET['id'];
$query = mysql_query("SELECT *FROM advertisement WHERE id = $id");
while($row = mysql_fetch_assoc($query)){
array_push($data,$row['id']);
}
return $data;
}
var_dump($data);
//echo advert($data['id']);
?>
Hi guys I´m new at stackoverflow and also new at Jquery
Well hope I can make myself understandable. Here is what I want: I have made a query to my MySQL db, using a class with PHP
public function User($id) {
$this->connect_db_web($conn);
$sql = mysql_query("SELECT * FROM users WHERE id='".$id."'");
while ($values = mysql_fetch_array($sql)) {
$arr[]=array(
'id'=>$values['idUsers'],
'name'=>$values['name'],
'name2'=>$values['name2'],
'lname'=>$values['lname'],
'lname2'=>$values['lname2'],
'email'=>$values['email'],
'phone'=>$values['phone'],
'address'=>$values['address'],
'bday'=>$values['bday'],
'password'=>$values['password']
);
}
echo '{"user":'.json_encode($arr).'}';
}
Then I have a php code where I call this function
$name = $user->User($id);
I think this works ok (if I´m wrong please help). Now what I´m really trying to do is getting the values from the JSON array into specific divs, example:
$.getJSON("user.php",function(data){
$.each(data.user, function(i,user){
name = user.name;
$(name).appendTo('#getname');
});
});
And inside my HML i Have a <p id="getname"></p>wich is the tag I want the value to be displayed
But no value is displayed, why?, what am I doing wrong?
Thanks for the help I apreciate it
Your JSON is malformed. You are appending a bunch of objects {.1.}{.2.}{.3.}. Instead, try {"users":[{.1.},{.2.},{.3.}]}.
In PHP you'll do something like this (note that I've changed the response type to JSON-P rather than JSON by adding a callback parameter):
public function User($id) {
$users = array();
$this->connect_db_web($conn);
$sql = mysql_query("SELECT * FROM users WHERE id='".$id."'");
while ($values = mysql_fetch_array($sql)) {
$users[] = array(
'id'=>$values['idUsers'],
'name'=>$values['name']
// etc.
);
}
$obj['users'] = $users;
$callback = (empty($_GET["callback"])) ? 'callback' : $_GET["callback"];
echo $callback . '(' . json_encode($obj) . ');';
}
Then you'll be able to do:
$.getJSON("user.php?callback=",function(data){
$.each(data.users, function(i,user){
$('#getname').append(user.name);
});
});
probably safer to do like this:
echo json_encode(array("user" => $arr));
on the other end you would receive an object which, I would suggest iterating like this:
var k;
for (k in data.user){
$("#getname").append($("<span></span>").html(data.user[k].name));
}
Given that you are fetching information for one user only, following I would suggest
$id = (int) $_GET["id"]; // or wherever you get it from.
if ($r = $db->mysql_fetch_assoc()){
$response = array(
"name" => $r["name"];
);
echo json_encode($response);
} else {
echo json_encode(array("error" => "Could not get name for user " . $id));
}
Then, on front-end, all you need to do is:
if (typeof(data.name) != "undefined"){
$("#getname").html(data.name);
} else if (typeof(data.error) != "undefined"){
$("#getname").html(data.error); //or handle otherwise
}
You've misinterpreted your JSON structure. You're appending your DB rows to an array, and embedding that inside an object. If you'd do a console.log(user) inside your .getJSON call, you'd see you'll have to do:
user[0].name
instead. As well, your code assumes that the user ID exists, and returns data regardless of how many, or how few, rows there actually are in the result set. At minimum your JS code code should check users.length to see if there ARE are any rows to begin with. Beyond that, unless you're doing it in another section of code somewhere, that $id value is probably coming from the web page, which means your query is vulnerable to SQL injection attacks.
OK got it,
was a php code error and JSON structre as marc said, here I´m gonna post what finally I had
PHP Class
public function User() {
$users = array();
$this->connect($conn);
$sql = mysql_query("SELECT * FROM users WHERE id='1'");
$values = mysql_fetch_array($sql);
$users[] = array(
'id'=>$values['id'],
'name'=>$values['name'],
'name2'=>$values['name2'],
'lname'=>$values['lname'],
...//rest of values
);
echo json_encode($users);
}
PHP module to get class
include"class.php";
$user = new Users();
$user->User();
Now how did I got the values using JQuery
$.getJSON('user.php', function(data){
$('wherever_you_want_to_point_at').text(data[0].name);
});
Hope it helps someone,
Thanks again guys, very very helpful
Take care you all
Can you do that? I just tried but it doesnt seem to work.
I have dbc.php included at top of my page, and in dbc.php at the bottom i created this function:
function getUserInfo($id) {
$thaString = mysql_query("SELECT * FROM users WHERE id = '$id'");
$thaString2 = mysql_query("SELECT * FROM users_profile WHERE uID = '$id'");
$showUR = mysql_fetch_array($thaString);
$showURP = mysql_fetch_array($thaString2);
}
So it would be easier for me to call them instead of running the queries all the time when i need them in other pages..
But when i try to do:
getUserInfo($showInfo["bID"]);
echo $showUR["full_name"];
I dont get any result, is there a smarter way to do this, if so how?
It's an issue of scope: $showUR is set inside getUserInfo(), so it's not available to the echo outside the function. There are lots of potential modifications you could make, but you may want to assign your values into an array and then return that array:
function getUserInfo($id) {
$user = array();
$thaString = mysql_query("SELECT * FROM users WHERE id = '$id'");
$thaString2 = mysql_query("SELECT * FROM users_profile WHERE uID = '$id'");
$user['showUR'] = mysql_fetch_array($thaString);
$user['showURP'] = mysql_fetch_array($thaString2);
return $user;
}
$user = getUserInfo($showInfo["bID"]);
echo $user['showUR']["full_name"];
Your functions have to return something for the values to be used, or $showUR and $showURP will just get lost once the function exits (ie: the scope will change). Something like:
function someFunc($arg) {
return "Hello, I am {$arg}";
}
$showUR = someFunc('name');
echo $showUR;
And please don't call stuff $thaString. First because it's a misnomer (mysql_query() doesn't return a string, it returns a resource or a boolean), Second because "tha" is so lame.
Let your function return the variable.
And then use $showUR = getUserInfo(...)
If you declare them outside the function, and then as globals inside the function you should be able to use them as you are now.